I’m new to Django (and Python), and am trying to figure out how to conditionalize certain aspects of form validation. In this case, there’s a HTML interface to the application where the user can choose a date and a time from widgets. The clean method on the form object takes the values of the time and date fields and turns them back into a datetime.
In addition to the HTML interface, there’s also an iPhone client making calls into the application, and I’d like to pass a UNIX timestamp-style time value in.
My form code looks like this:
class FooForm(forms.ModelForm):
foo_date = forms.CharField(required=True, widget=forms.RadioSelect(choices=DATE_CHOICES))
foo_time = forms.CharField(required=True, widget=SelectTimeWidget())
foo_timestamp = forms.CharField(required=False)
How do I make foo_date and foo_time required unless foo_timestamp is provided?
This is done with the
cleanmethod on the form. You need to setfoo_dateandfoo_timetorequired=False, though, becausecleanis only called after every field has been validated (see also the documentation).