Skip to content Skip to sidebar Skip to footer

Django Form Validation: Making "required" Conditional?

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 wher

Solution 1:

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).

classFooForm(forms.Form)
    # your field definitions

    def clean(self):
        data = self.cleaned_data
        ifdata.get('foo_timestamp', None) or (data.get('foo_date', None) and data.get('foo_time', None)):
            returndataelse:
            raise forms.ValidationError('Provide either a date and time or a timestamp')

Solution 2:

I found myself needing a "standard" way to do this, as my forms have several conditionally required fields. So I created a superclass with the following method:

defvalidate_required_field(self, cleaned_data, field_name, message="This field is required"):
    if(field_name in cleaned_data and cleaned_data[field_name] isNone):
        self._errors[field_name] = self.error_class([message])
        del cleaned_data[field_name]

And then in my form's clean method I have:

defclean(self):
    cleaned_data = super(FormClass, self).clean()
    if(condition):
        self.validate_required_field(cleaned_data, 'field_name')

It's worked perfectly for me so far.

Post a Comment for "Django Form Validation: Making "required" Conditional?"