Django 6.1.3

10.5 Templates and forms

The full_clean pipeline and ValidationError

In what exact order do to_python, validate, run_validators, clean_<field>, and BaseForm.clean execute — and what happens to cleaned_data when one field fails?

Calling BaseForm.is_valid is a one-liner: "return self.is_bound and not self.errors". Accessing BaseForm.errors checks if self._errors is None: and triggers full_clean exactly once, caching the resulting ErrorDict on "self._errors" so repeated calls to is_valid() or "form.errors" never re-run validation or database queries!

The three stages of BaseForm.full_clean

Open BaseForm.full_clean (lines 324–367 of django/forms/forms.py). After initializing "self._errors = ErrorDict(...)" and "self.cleaned_data = {}" (and short-circuiting immediately if unbound, or if "empty_permitted" is True and "not self.has_changed()" — the exact rule that lets blank extra formset rows pass!), full_clean runs three methods in strict sequence:

  1. Stage 1 — BaseForm._clean_fields: Iterates every (name, bf) pair from _bound_items() in field order. First it calls Field._clean_bound_field -> Field.clean, which runs three sub-steps on the raw widget string:
    • Field.to_python converts the raw HTML string into a typed Python value (for example, "1" -> int(1), or "2" -> "Desk" instance via ModelChoiceField.to_python!).
    • Field.validate enforces field-level constraints like "required" (raising ValidationError if the value is in empty_values and required=True).
    • Field.run_validators runs every validator in "self.validators", collecting all validator errors into a list rather than stopping at the first validator failure.
    • If Field.clean succeeds, Django stores the Python value in cleaned_data (self.cleaned_data[name] = value), then checks hasattr(self, f"clean_{name}") and calls your custom "clean_<field>()", storing its return value back into cleaned_data[name]!
  2. Stage 2 — BaseForm._clean_form: Runs BaseForm.clean — your cross-field validation hook, where "desk/"'s "StoryForm.clean" verifies that the chosen "Reporter" actually belongs to the chosen "Desk". Notice that Stage 2 runs even when Stage 1 recorded field errors! Any ValidationError raised directly from clean() is passed to BaseForm.add_error(None, e), attaching it under NON_FIELD_ERRORS (NON_FIELD_ERRORS, "__all__") unless the error itself wraps a {field_name: message} dict.
  3. Stage 3 — BaseForm._post_clean: A no-op on plain Form, overridden by BaseModelForm._post_clean to copy "cleaned_data" onto "self.instance" and run model validation, uniqueness checks, and constraint checks.
Figure 10.3 Every validation outcome and microsecond bar is parsed directly from ch10-presentation and ch10-bench. Notice why validating "StoryForm" costs 1,950.2 us (120.14x an unbound "PlainForm"): three ModelChoiceFields query "Desk", "Reporter", and "Edition", "StoryForm.clean" reads "reporter.desk", and _post_clean queries the database to verify uniqueness on "slug".

Why BaseForm.add_error deletes keys from cleaned_data

Look closely at lines 314–316 of BaseForm.add_error:

self._errors[field].extend(error_list)
if field in self.cleaned_data:
    del self.cleaned_data[field]

Whenever any field fails Field.clean, fails "clean_<field>()", or receives a field-specific error via BaseForm.add_error ("self.add_error('headline', ...)"), Django removes that key from "cleaned_data" immediately. That guarantees "cleaned_data" never contains a half-validated or invalid value — and it explains the #1 KeyError trap inside custom clean() methods: never write "self.cleaned_data['headline']" inside clean(), because if "headline" failed Stage 1 it is no longer in the dictionary! Always use "cleaned.get('headline')" (just as "StoryForm.clean" uses "cleaned.get('desk')" and "cleaned.get('reporter')").

Watch both Stage 1 ("clean_headline" rejecting "ALL CAPS ALERT" and deleting "headline" from "cleaned_data") and Stage 2 ("StoryForm.clean" catching City Hall reporter "Cora" assigned to "Metro" under "__all__") fire in the same full_clean run on "desk/":

Recorded on Django 6.1.3 ch10-presentation script
5. Three-stage full_clean pipeline on StoryForm
  invalid_submit: is_valid=False headline_in_cleaned_data=False cleaned_keys=['body', 'desk', 'edition', 'priority', 'reporter', 'slug']
  error_dict = {'headline': [{'message': 'Use sentence case, not all-caps headlines.', 'code': ''}], '__all__': [{'message': 'Cora files for City Hall, not Metro.', 'code': ''}]}
  valid_submit: is_valid=True errors={} cleaned_headline='Council approves ferry dock'

And look at the full timing breakdown from ch10-bench showing how pure-Python field validation (37.9 us) compares against database-backed ModelForm validation (1,950.2 us):

Recorded on Django 6.1.3 ch10-bench script
2. Form instantiation and full_clean() cost (7 trials, us/op)
  form_op                             median_us      rel
  PlainForm() unbound (deepcopy)           16.2    1.00x
  PlainForm(post).is_valid()               37.9    2.33x
  StoryForm() unbound (7 fields)          120.0    7.39x
  StoryForm(post).is_valid() [DB]        1950.2  120.14x
  FormSet(10 PlainForms).is_valid()       565.1   34.81x

Notice that "StoryForm" did not declare a single CharField or ModelChoiceField manually — it inherited from ModelForm, whose metaclass synthesized all seven form fields from "Story._meta" and whose _post_clean method hides a notorious in-memory mutation trap. We open ModelForm next in ModelForm, _post_clean, and save.