Django provides two way to add custom validation rules to a form.
clean() : If added as a form sub-class, lets you access and validate all fields in the form.
clean_<fieldname>() : Lets you define validation method for the , it's added as sub-class in form.
You can have your custom validation code in these classes. Once you detected an invalid data raise error. Use this method if you need to deal with multiple inputs.
raise forms.ValidationError("<error messge>", code="<error_code>",)
These functions gives the absolute power to deal with forms. Example usage:
# Form fields
if field < 100:
raise forms.ValidationError("you can't go below 100", code="field1",)
If your requirement is to validate a single field this is right solution. It allows all the functions you can do with the clean() but restricts access only to the single field.
# Form fields
# user_name is the form field
user_name = self.cleaned_data['user_name']
if user_name is None:
raise forms.ValidationError("Give me a username", code="user_name",)
Flow of control
You don't have to go for a long vacation to be in a situation where you have to use
clean() together or
clean_<fieldname>() multiple times inside a same form. Here's how they get executed.
clean_<fieldname>() are executed before executing the main
- Once a
clean_<fieldname>() is executed the field is removed from the
If using multiple clean method make sure you check if field exists in the
cleaned_data before you grab it, it can result in KeyError if the fields clean method removed it.