[Answer]-Django – customised validation error

1👍

clean_voluntary_finish_date is only called when that particular field is validated, so others may not yet be “cleaned”. This means that when you use self.cleaned_data.get('voluntary_date_display_type'), that field is not cleaned yet, so there is no key in cleaned_data, and the .get() method will return None.

You need to use the normal clean() method when validation depends on more than one field; as stated in the django forms reference under “Cleaning and validating fields that depend on each other”:

Suppose we add another requirement to our contact form: if the
cc_myself field is True, the subject must contain the word “help”. We
are performing validation on more than one field at a time, so the
form’s clean() method is a good spot to do this. Notice that we are
talking about the clean() method on the form here, whereas earlier we
were writing a clean() method on a field.
It’s important to keep the
field and form difference clear when working out where to validate
things. Fields are single data points, forms are a collection of
fields.

By the time the form’s clean() method is called, all the individual
field clean methods will have been run (the previous two sections), so
self.cleaned_data will be populated with any data that has survived so
far. So you also need to remember to allow for the fact that the
fields you are wanting to validate might not have survived the initial
individual field checks.

All you have to do is:

def clean(self):
    cleaned_data = super(YourFormClassName, self).clean()
    # copy and paste the rest of your code here
    return cleaned_data # this is not required as of django 1.7

Leave a comment