Validation happens at multiple layers: HTML5 client hints, Django form fields, model clean() methods, and database constraints. Never trust the client alone.
Form-level validation
def clean_title(self):
title = self.cleaned_data["title"]
if "spam" in title.lower():
raise ValidationError("Title not allowed")
return title
Displaying errors
{{ form.non_field_errors }} for form-wide issues; {{ form.title.errors }} per field. Re-render the form with errors on failed POST—preserve user input.
Important interview questions and answers
- Q: clean vs clean_fieldname?
A: Field cleaners run per field; clean() validates cross-field rules (e.g. password match). - Q: Model validation on save?
A: Callfull_clean()before save in custom code—ModelForm does this automatically. - Q: ValidationError in models?
A: Raise in clean() methods—surfaces in forms and admin.
Self-check
- Why re-render the form after validation fails?
- Where add cross-field validation?
Tip: Re-display bound forms on validation failure so users do not retype everything—pass the same form instance back to the template.