[Django]-Why does Django throw a KeyError on this form validation?

4👍

You should always check that key exists in cleaned_data before using it in clean() method. You’re not guaranteed that value is present in cleaned_data array if previous validations has not passed.

Documentation: https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

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.

Leave a comment