How to Use clean Method in Django Form for Validation
In Django forms, use the
clean method to add custom validation that involves multiple fields or complex logic. Override clean in your form class, call super().clean() to get cleaned data, then raise ValidationError if validation fails.Syntax
The clean method is overridden inside a Django form class to perform custom validation on the entire form data after individual field validations.
Inside clean, you call super().clean() to get the cleaned data dictionary, then add your validation logic. If validation fails, raise ValidationError.
python
def clean(self): cleaned_data = super().clean() # custom validation logic here if some_condition: raise ValidationError('Error message') return cleaned_data
Example
This example shows a form with two fields: start_date and end_date. The clean method checks that end_date is after start_date. If not, it raises a validation error.
python
from django import forms from django.core.exceptions import ValidationError class DateRangeForm(forms.Form): start_date = forms.DateField() end_date = forms.DateField() def clean(self): cleaned_data = super().clean() start = cleaned_data.get('start_date') end = cleaned_data.get('end_date') if start and end and end <= start: raise ValidationError('End date must be after start date.') return cleaned_data
Output
If end_date is before or equal to start_date, form.is_valid() will be False and form.errors will include 'End date must be after start date.'
Common Pitfalls
- Not calling
super().clean()can cause missing cleaned data and errors. - Raising
ValidationErrorwithout returningcleaned_databreaks form processing. - Trying to validate individual fields in
cleaninstead of theirclean_fieldnamemethods. - Not checking if fields exist in
cleaned_databefore using them can cause errors.
python
def clean(self): # Wrong: missing super call if self.cleaned_data.get('field') == 'bad': raise ValidationError('Error') return self.cleaned_data # Correct way: def clean(self): cleaned_data = super().clean() if cleaned_data.get('field') == 'bad': raise ValidationError('Error') return cleaned_data
Quick Reference
Tips for using clean method in Django forms:
- Always call
super().clean()first to get cleaned data. - Use
cleanto validate multiple fields together. - Raise
ValidationErrorwith a clear message on failure. - Return the cleaned data dictionary at the end.
- Use
clean_fieldnamemethods for single field validation.
Key Takeaways
Override the clean method in your Django form to validate multiple fields together.
Always call super().clean() to access cleaned data before adding custom validation.
Raise ValidationError inside clean to stop form submission with an error message.
Return the cleaned_data dictionary at the end of the clean method.
Use clean_fieldname methods for single field validation, clean for cross-field checks.