Django Form Validation
Built-in field checks — required, max length, valid email — cover a lot, but real forms have business rules: a username must not be taken, an end date must come after a start date, a discount code must exist. Django gives you hooks at three levels to add your own checks, and they all report errors the same way: by raising ValidationError.
How validation runs
When you call form.is_valid() (or access form.errors), Django runs these steps:
| Step | Where | Purpose |
|---|---|---|
1. field.to_python() |
each field | convert the raw string ("42" → 42) |
2. field.validate() + validators |
each field | built-in rules and validators=[…] |
3. clean_<fieldname>() |
your form | custom rules for one field |
4. clean() |
your form | rules involving several fields |
| 5. model validation | ModelForms only | unique, model clean(), constraints |
A field that fails an earlier step is removed from cleaned_data, so later steps must not assume it's there.
Reusable validators
A validator is a function that raises ValidationError for bad input. Attach it to any field (form or model) with validators=[...]. Django ships ready-made ones such as MinLengthValidator, RegexValidator and MaxValueValidator:
import django
from django.conf import settings
settings.configure()
django.setup()
from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
def not_blank_words(value):
if value.strip().lower() in {"test", "asdf", "none"}:
raise ValidationError("Please enter a real value, not %(value)r.", params={"value": value})
phone_validator = RegexValidator(r"^0\d{9}quot;, "Phone numbers have 10 digits and start with 0.")
class ProfileForm(forms.Form):
nickname = forms.CharField(validators=[not_blank_words])
phone = forms.CharField(validators=[phone_validator])
for data in [{"nickname": "Bee", "phone": "0912345678"},
{"nickname": "asdf", "phone": "+84 91"}]:
form = ProfileForm(data)
print(form.is_valid(), dict((f, e[0]) for f, e in form.errors.items()) or form.cleaned_data)True {'nickname': 'Bee', 'phone': '0912345678'}
False {'nickname': "Please enter a real value, not 'asdf'.", 'phone': 'Phone numbers have 10 digits and start with 0.'}
clean_<field>(): one field, custom logic
Define a method named clean_<fieldname> to validate — and optionally transform — a single field. It reads self.cleaned_data[...], raises ValidationError if needed, and must return the cleaned value:
import django
from django.conf import settings
settings.configure()
django.setup()
from django import forms
TAKEN = {"admin", "root", "linh"}
class SignupForm(forms.Form):
username = forms.CharField(max_length=20)
coupon = forms.CharField(required=False)
def clean_username(self):
name = self.cleaned_data["username"].strip().lower() # normalise
if name in TAKEN:
raise forms.ValidationError("That username is already taken.")
return name
def clean_coupon(self):
code = self.cleaned_data["coupon"].upper()
if code and not code.startswith("SAVE"):
raise forms.ValidationError("Unknown coupon code.", code="bad_coupon")
return code
for data in [{"username": " Mai ", "coupon": "save10"},
{"username": "LINH", "coupon": "FREE"}]:
form = SignupForm(data)
if form.is_valid():
print("ok:", form.cleaned_data)
else:
print("errors:", {f: e[0] for f, e in form.errors.items()})
print("codes: ", form.errors.as_data()["coupon"][0].code)ok: {'username': 'mai', 'coupon': 'SAVE10'}
errors: {'username': 'That username is already taken.', 'coupon': 'Unknown coupon code.'}
codes: bad_coupon
Error codes let tests and templates react to a specific error without matching the message text.
clean(): rules across several fields
When a rule involves more than one field — passwords must match, end after start — override clean(). Call super().clean() first, use .get() because a field may already have failed, and either raise ValidationError (a non-field error) or attach the error to a specific field with add_error():
import django, datetime
from django.conf import settings
settings.configure()
django.setup()
from django import forms
class BookingForm(forms.Form):
check_in = forms.DateField()
check_out = forms.DateField()
guests = forms.IntegerField(min_value=1)
pets = forms.BooleanField(required=False)
def clean(self):
cleaned = super().clean()
start, end = cleaned.get("check_in"), cleaned.get("check_out")
if start and end and end <= start:
raise forms.ValidationError("Check-out must be after check-in.")
if cleaned.get("pets") and cleaned.get("guests", 0) > 4:
self.add_error("pets", "Pets are only allowed for groups of up to 4.")
return cleaned
tests = [
{"check_in": "2026-07-01", "check_out": "2026-07-05", "guests": "2"},
{"check_in": "2026-07-05", "check_out": "2026-07-01", "guests": "2"},
{"check_in": "2026-07-01", "check_out": "2026-07-03", "guests": "6", "pets": "on"},
{"check_in": "July 1st", "check_out": "2026-07-03", "guests": "1"},
]
for data in tests:
form = BookingForm(data)
if form.is_valid():
nights = (form.cleaned_data["check_out"] - form.cleaned_data["check_in"]).days
print("valid,", nights, "nights")
else:
print("non-field:", form.non_field_errors(), "| fields:", {f: e[0] for f, e in form.errors.items() if f != "__all__"})valid, 4 nights
non-field: <ul class="errorlist nonfield"><li>Check-out must be after check-in.</li></ul> | fields: {}
non-field: | fields: {'pets': 'Pets are only allowed for groups of up to 4.'}
non-field: | fields: {'check_in': 'Enter a valid date.'}
In a template, show non-field errors with {{ form.non_field_errors }} at the top of the form.
Validation on the model
Rules that must hold no matter which form (or script) changes the data belong on the model: a model clean() method, field validators and database constraints. ModelForms run them automatically during is_valid():
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django import forms
from django.db import models
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator
class Discount(models.Model):
code = models.CharField(max_length=20)
percent = models.IntegerField(validators=[MaxValueValidator(90)])
min_order = models.IntegerField(default=0)
class Meta:
app_label = "demo"
def clean(self):
if self.percent >= 50 and self.min_order < 100:
raise ValidationError({"min_order": "Big discounts need a minimum order of 100."})
class DiscountForm(forms.ModelForm):
class Meta:
model = Discount
fields = ["code", "percent", "min_order"]
for data in [{"code": "HALF", "percent": "50", "min_order": "150"},
{"code": "HALF", "percent": "50", "min_order": "20"},
{"code": "ALL", "percent": "100", "min_order": "500"}]:
form = DiscountForm(data)
print(form.is_valid(), {f: e[0] for f, e in form.errors.items()})True {}
False {'min_order': 'Big discounts need a minimum order of 100.'}
False {'percent': 'Ensure this value is less than or equal to 90.'}
Tip: Client-side checks (HTML
required,min, JavaScript) improve the user experience, but they can be bypassed. Server-side validation in Django is the one that actually protects your data.
Test yourself
What must a clean_<field>() method return?
- True or False
- Nothing
- The cleaned value for that field
- The whole cleaned_data dict
Where do you check that check_out is after check_in?
- clean_check_in()
- clean()
- A widget
- The template
Inside clean(), why use cleaned_data.get("check_in") instead of cleaned_data["check_in"]?
- It's faster
- The field may have failed earlier validation and be missing
[]isn't allowed on dicts- To convert it to a date