Hello,
I've a problem with the admin and a custom clean method in one of my Models.
Here's the code:
class Related(models.Model):
parent = models.OneToOneField('Parent')
...
class Parent(models.Model):
simple_mode = models.BooleanField(
default=True
)
simple_value = models.CharField(
null=True, blank=True
)
...
def clean(self):
if self.simple_mode and not simple_value:
raise ValidationError(
"If simple_mode is selected simple_value is required."
)
if not self.simple_mode and not Related.objects.filter(parent=self).exists():
raise ValidationError(
"If simple_mode is NOT selected a Related model MUST exists."
)
The admin code is really simple. The ParentAdmin includes the inline to add/change the Related object (used only if simple_mode is set to False).
Here's the code:
class RelatedAdmin(admin.StackedInline):
model = Related
...
class ParentAdmin(admin.ModelAdmin):
inlines = (RelatedAdmin, )
...
This works fine if simple_mode is set to True and there's no need to add the Related model.
The problem is when I set simple_mode to False: the admin form always return the second ValidationError in Parent.clean(), even if all the fields in RelatedAdmin are correctly filled.
From my understanding this happens because, in the admin, the Parent is always validated and saved before all the inlines: so the Parent.clean() method is called before adding the Related model, obviously resulting in the ValidationError.
Any ideas to solve the problem?
--
e.p.