I have a pretty big form, wich has two possibilities. It is a form for an event, and the event location can be picked from a combobox (ModelChoice query). However, there is the possibility for the user to check the “New location” checkbox, and then the form shows the fields neccessary to insert the new location as well, and the “existing locations” combobox is reset. Now, this all works very nice with javascript (jQuery), but my problem is how to validate the unused fields in the form.
To put it simple> I have i.e. 7 form fileds, 3 of them are always mandatory (event type, datetime etc), while the other depend on the state of the checkbox “new location”: if new_location is checked> validate the location etc fields, and ignore the rest (allow them to be empty), otherwisw ignore the location fields and validate the rest.
class EventForm(ModelForm):
area = forms.ModelChoiceField(
queryset=Area.objects.order_by('name').all(),
empty_label=u"Please pick an area",
label=u'Area',
error_messages={'required':u'The area is mandatory!'})
type = forms.ModelChoiceField(
queryset=SportType.objects.all(),
empty_label=None,
error_messages={'required':'Please pick a sport type!'},
label=u"Sport")
#shown only if new_location is unchecked - jQuery
location = forms.ModelChoiceField(
queryset=Location.objects.order_by('area').all(),
empty_label=u"Pick a location",
error_messages={'required':'Please pick a location'},
label=u'Location')
#trigger jQuery - hide/show new location field
new_location = forms.BooleanField(
required=False,
label = u'Insert new location?'
)
address = forms.CharField(
label=u'Locatio address',
widget=forms.TextInput(attrs={'size':'30'}),
error_messages={'required': 'The address is required'})
location_description = forms.CharField(
label=u'Brief location description',
widget=forms.Textarea(attrs={'size':'10'}),
error_messages={'required': 'Location description is mandatory'})
class Meta:
model = Event
fields = (
'type',
'new_location',
'area',
'location',
'address',
'location_description',
'description',
)
I ended up using just a normal form (not ModelForm) and custom validation with
clean(self)depending on the state of the checkbox, I think it is the right way to go. Then withself._errors["address"]=ErrorList([u'Some custom error'])I was able to fully customise the various errors that could come up during the validation process.