views:

183

answers:

1

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?

+5  A: 

This is done with the clean method on the form. You need to set foo_date and foo_time to required=False, though, because clean is only called after every field has been validated (see also the documentation).

class FooForm(forms.Form)
    # your field definitions

    def clean(self):
        data = self.cleaned_data
        if data.get('foo_timestamp', None) or (data.get('foo_date', None) and data.get('foo_time', None)):
            return data
        else:
            raise forms.ValidationError('Provide either a date and time or a timestamp')
piquadrat
Thanks, I was thinking `clean` was probably the place to do this. Is it possible, though, to have the validation error against the `foo_date` and `foo_time` fields, versus a general form validation error?Thanks, Chris
ChrisW
That's explained in the second example in the docs I linked to
piquadrat
self.RTFM; thanks, I'll dig in.
ChrisW