The Analogy: A Bank's New-Account Intake Window
Picture the intake window at a bank branch. A walk-in customer slides a filled-out application through the slot, and a clerk sits behind the glass with a checklist. Nothing the customer wrote is trusted on sight: the clerk reads each box against a rule -- is there a name, is the age a whole number and at least eighteen, is the opening deposit a positive amount -- and only what survives the checklist gets transcribed into the bank's ledger. Everything on the slip arrived as ink from a stranger; the checklist is the only thing standing between that ink and the permanent record.
The clerk does two different kinds of checking. First, box by box: this field is required, that one must be a number, this date must be real. That is field-level validation, the per-box rule. Second, the clerk compares boxes against each other: a premium account requires a minimum deposit, a joint account needs a second signatory. That cross-box check cannot live in any single box because it depends on several at once -- it is form-level validation. Both must pass before anything is written down.
When every rule passes, the clerk does not copy the raw slip. They produce a clean, typed record: the scrawled "1,500" becomes an integer, the ticked box becomes a definite yes, the written birthday becomes a real date. That transcribed record -- not the original ink -- is what flows downstream to open the account. If any rule fails, the slip comes back through the slot with a specific note pinned to each offending box, and the customer fixes exactly those and resubmits.
The failure mode is a clerk who skips the checklist and types whatever the customer wrote straight into the ledger. A blank name, an age of "xx", a negative deposit -- all sail through and corrupt every report built on that ledger later. Worse is the clerk who honors a box the customer should never have controlled: if the slip has an "account tier" field and the clerk copies it verbatim, the customer has just granted themselves premium standing that nobody approved. Trusting input you did not validate is how bad data gets in; trusting fields you did not intend to expose is how privilege gets stolen.
Syntax or Core Structure
A Django Form declares fields; is_valid() runs the checklist; cleaned_data holds the typed, trusted record. A ModelForm derives those fields from a model so you do not repeat them.
from django import forms
class AccountForm(forms.Form):
name = forms.CharField(max_length=100)
age = forms.IntegerField(min_value=18)
deposit = forms.IntegerField(min_value=1)
premium = forms.BooleanField(required=False)
def clean(self): # form-level: cross-field rule
cleaned = super().clean()
if cleaned.get("premium") and cleaned.get("deposit", 0) < 1000:
raise forms.ValidationError("premium requires a deposit of at least 1000")
return cleaned
Reduced to a plain-Python REPL, the checklist is just a function: convert each field to its type, apply the per-field rule, then the cross-field rule, and return either a typed record or a map of per-box notes.
def to_int(v):
if not str(v).lstrip("-").isdigit():
raise ValueError("enter a whole number")
return int(v)
def clean_form(raw):
cleaned, errors = {}, {}
# name: required, trimmed
name = raw.get("name", "").strip()
if not name:
errors["name"] = "this field is required"
else:
cleaned["name"] = name
# age: whole number, at least 18
try:
age = to_int(raw.get("age", ""))
if age < 18:
errors["age"] = "must be at least 18"
else:
cleaned["age"] = age
except ValueError as ex:
errors["age"] = str(ex)
# deposit: whole number, greater than 0
try:
dep = to_int(raw.get("deposit", ""))
if dep <= 0:
errors["deposit"] = "must be greater than 0"
else:
cleaned["deposit"] = dep
except ValueError as ex:
errors["deposit"] = str(ex)
# premium: optional checkbox
cleaned["premium"] = raw.get("premium", "") == "on"
# form-level cross-field rule
if not errors and cleaned["premium"] and cleaned["deposit"] < 1000:
errors["__all__"] = "premium requires a deposit of at least 1000"
return cleaned, errors
raw = {"name": " Ada ", "age": "30", "deposit": "1500", "premium": "on"}
cleaned, errors = clean_form(raw)
print("valid:", not errors)
print("cleaned:", " ".join(f"{k}={cleaned[k]}" for k in ("name", "age", "deposit", "premium")))
Output:
valid: True
cleaned: name=Ada age=30 deposit=1500 premium=True
The raw slip held strings and whitespace; cleaned_data holds a trimmed str, two real ints, and a genuine bool. Nothing downstream ever touches the original ink -- it works only from the transcribed record.
Technical Depth: Field Cleaning, clean() and the Order of Checks
Every field is converted before it is validated
A form field does two things in order: turn the raw string into a Python value, then check that value. If conversion fails, the value rule never runs -- you get "enter a whole number", not "must be at least 18".
| Field | Python type after cleaning | Typical rule |
|---|---|---|
| CharField | str | max_length, non-empty |
| IntegerField | int | min_value, max_value |
| BooleanField | bool | required means must be True |
| DateField | date | real calendar date |
| EmailField | str | valid address shape |
Field errors versus non-field errors
A per-box rule lives in clean_<field>() and attaches its error to that box. A cross-box rule lives in clean() and, when it fails without naming a field, attaches to the special __all__ bucket -- the non-field errors. The batch below runs the same clean_form over five slips and prints, for each, either the accepted essentials or every note keyed by its box.
subs = [
{"name": "Ada", "age": "30", "deposit": "1500", "premium": "on"},
{"name": "", "age": "30", "deposit": "1500", "premium": ""},
{"name": "Bob", "age": "16", "deposit": "50", "premium": ""},
{"name": "Cara", "age": "40", "deposit": "500", "premium": "on"},
{"name": "Dan", "age": "xx", "deposit": "100", "premium": ""},
]
for s in subs:
cleaned, errors = clean_form(s)
if errors:
print("REJECT", ";".join(f"{k}:{errors[k]}" for k in errors))
else:
print("OK", cleaned["name"], cleaned["deposit"])
Output:
OK Ada 1500
REJECT name:this field is required
REJECT age:must be at least 18
REJECT __all__:premium requires a deposit of at least 1000
REJECT age:enter a whole number
The last two rows are the key contrast: Dan's age fails conversion so the value rule is never reached, while Cara's fields each pass and only the cross-field rule rejects her, landing in __all__ because no single box is at fault.
Real World Example: A Deposit Intake Desk and What It Lets Through
A branch processes a morning's applications. Each valid one opens an account and adds its deposit to the day's total; each invalid one is turned away with the first box that failed. The program below runs the day, then reports what was accepted and tallies rejections by reason -- the numbers a branch manager would actually read.
APPS = [
{"name": "Ada", "age": "30", "deposit": "1500", "premium": "on"},
{"name": "", "age": "22", "deposit": "300", "premium": ""},
{"name": "Bob", "age": "16", "deposit": "900", "premium": ""},
{"name": "Cara", "age": "45", "deposit": "500", "premium": "on"},
{"name": "Dan", "age": "28", "deposit": "2000", "premium": "on"},
{"name": "Eve", "age": "35", "deposit": "0", "premium": ""},
]
accepted_names, total, reasons, order = [], 0, {}, []
for app in APPS:
cleaned, errors = clean_form(app)
if errors:
reason = next(iter(errors)) # the first box that failed
if reason not in reasons:
order.append(reason)
reasons[reason] = reasons.get(reason, 0) + 1
else:
accepted_names.append(cleaned["name"])
total += cleaned["deposit"]
print("accepted:", len(accepted_names))
print("accepted names:", ",".join(accepted_names))
print("total deposits:", total)
print("rejected:", sum(reasons.values()))
for r in order:
print(f" {r}: {reasons[r]}")
Output:
accepted: 2
accepted names: Ada,Dan
total deposits: 3500
rejected: 4
name: 1
age: 1
__all__: 1
deposit: 1
Two of six applications open accounts, for a combined 3500, and the four rejections split evenly across four distinct reasons. Only Ada and Dan clear every gate, including the premium-deposit floor that turns Cara away even though each of her individual boxes was fine. The manager's report is built entirely from cleaned_data and the error map -- never from the raw slips.
The reason tally is the useful part operationally: it tells you whether the desk is losing customers to a required field they keep leaving blank, an age gate, or a deposit floor they do not understand. Because the cross-field failure lands in __all__, it is counted separately from any single box, which is exactly right -- the fix is not to one field but to the combination.
This code has real flaws worth naming. It records only the first failing box per application (next(iter(errors))), so a slip that is wrong in three ways is filed under one reason and the tally understates the true error rate; real Django keeps a list of errors per field. The premium flag is read straight from the applicant's own submission and only gates a deposit minimum -- but if this were a ModelForm with fields = "__all__" over a model that had an is_staff or tier column, the applicant could set it themselves, the classic mass-assignment hole. There is no uniqueness check, so two applicants named "Ada" both open accounts. And the deposits are bare integers with no currency or overflow handling, so the 3500 total silently assumes every deposit is in the same units.
Common Mistakes
- Reading request.POST directly instead of a form. Raw POST values are strings with no guarantees. Bind a form and use
cleaned_data, which gives you converted types and enforced rules.
- Treating a form as valid without calling is_valid().
cleaned_datadoes not exist untilis_valid()has run. Accessing it first raisesAttributeError; skipping the check entirely trusts unvalidated input.
- Requiring a BooleanField for a checkbox. An unchecked box is simply absent from the POST body, so a required
BooleanFieldcan never validate. Userequired=False.
- Putting cross-field logic in a single clean_<field>(). A rule that depends on two fields belongs in
clean(); a per-field method cannot see the others reliably, because their cleaning order is not yours to assume.
- Raising a plain exception instead of ValidationError. Only
ValidationErroris caught and turned into a form error. A bareValueErrororassertbecomes a 500, not a friendly message.
- Using ModelForm with fields = "__all__". This exposes every model field, including ones the user must never set (
is_staff,balance,owner). List fields explicitly; treat"__all__"as a security smell.
- Validating uniqueness by hand and racing. Checking "does this email exist" in
clean()then saving leaves a gap where two requests both pass. Rely on a database unique constraint as the real guard.
- Forgetting to re-render the bound form on failure. On invalid POST you must return the same bound form so the user sees their input and the per-field errors, not a blank form that discards their work.
- Swallowing non-field errors in the template. Rendering only per-field errors hides
__all__messages, so a cross-field failure looks like nothing happened. Render non-field errors explicitly.
Best Practices
- Let cleaned_data be the only source of truth. After
is_valid(), read every value fromcleaned_data, never fromrequest.POST, so you always work with converted, validated types.
- List ModelForm fields explicitly. Name the fields you intend to accept; never
fields = "__all__". This closes mass-assignment by construction.
- Put per-field rules in clean_<field>() and cross-field rules in clean(). Match the rule's scope to the method's scope so errors attach to the right place.
- Raise ValidationError with clear, box-specific messages. Tell the user what to change and where; attach the error to the field when one is at fault.
- Back uniqueness with a database constraint. Use
unique=True(orUniqueConstraint) and let the form surface the integrity error, rather than a racy hand-check.
- Return the bound form on failure. Re-render with the submitted data and errors so the user can correct exactly what failed.
- Render non-field errors too. Always show
form.non_field_errorsso__all__messages are visible.
- Normalise in cleaning. Trim whitespace, lowercase emails, and canonicalise input in
clean_<field>()so stored data is consistent.
Practice Exercises
- Add a confirm-deposit field. Extend
clean_formwith adeposit_confirmvalue and a cross-field rule in theclean()stage that rejects when it does not equaldeposit; show the error lands in__all__.
- Collect all errors per field. Change the error map so each field holds a list of messages, and make a slip that is wrong in two ways report both; update the batch printer to show them.
- Close the mass-assignment hole. Add a
tierkey to the raw slips and show thatclean_formignores it unless it is an explicitly declared field, mirroring an allowlist ofModelFormfields.
- Tally by every reason, not the first. Rewrite the Real World summary so an application failing for two reasons increments both counts, and confirm the totals differ from the first-reason-only version.