Reputation: 1711
I'm using the Django admin interface and Modelform form validation.
I'm having an issue for one of my models, I can't figure out a way to have the inline forms check for uniqueness on a field. For example there are two inline objects with the the field 'name'. I'd like to raise a validation error if both contain the same name.
From what I can see, each inline is validated as a separate form so its hard to tie them in and check for this.
(Very) basic idea:
Class Parent
name charfield
inlines [Child]
Class Child
name charfield <- I'd like to make sure this is unqiue within the inlines
age intfield
Upvotes: 2
Views: 1140
Reputation: 2405
You write your own FormSet class, and make a clean callable:
class BaseDateFormSet(BaseInlineFormSet):
'''run some validation on the forms dates values'''
def clean(self):
super(BaseDateFormSet, self).clean()
if any(self.errors):
return
for form in self.forms:
start_date = form.cleaned_data.pop('start_date', None)
end_date = form.cleaned_data.pop('end_date', None)
if start_date and end_date:
if start_date >= end_date:
raise ValidationError("The end date is before the start date.")
To use, pass into the formset factory:
MyFormSet = inlineformset_factory(
<parent model class>, <model class>, extra=1, formset=BaseDateFormSet
)
Upvotes: 3