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 a one-liner: "return self. Accessing BaseForm.errors checks if self 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 (lines 324–367 of django/). After initializing "self and "self (and short-circuiting immediately if unbound, or if "empty_permitted" is True and "not self — the exact rule that lets blank extra formset rows pass!), full_clean runs three methods in strict sequence:
- Stage 1 —
BaseForm: Iterates every._clean_fields (name, bf)pair from_bound_items()in field order. First it callsField->._clean_bound_field Field.clean, which runs three sub-steps on the raw widget string:Field.to_pythonconverts the raw HTML string into a typed Python value (for example,"1"->int(1), or"2"->"Desk"instance viaModelChoiceField!)..to_python Field.validateenforces field-level constraints like"required"(raisingValidationErrorif the value is inempty_valuesandrequired=True).Fieldruns every validator in.run_validators "self, collecting all validator errors into a list rather than stopping at the first validator failure..validators" - If
Field.cleansucceeds, Django stores the Python value incleaned_data(self), then checks.cleaned_data[name] = value hasattr(self, f"clean_{name}")and calls your custom"clean_<field>()", storing its return value back intocleaned_data[name]!
- Stage 2 —
BaseForm: Runs._clean_form BaseForm.clean— your cross-field validation hook, where"desk/"'s"StoryFormverifies that the chosen.clean" "Reporter"actually belongs to the chosen"Desk". Notice that Stage 2 runs even when Stage 1 recorded field errors! AnyValidationErrorraised directly fromclean()is passed toBaseForm, attaching it under.add_error(None, e) NON_FIELD_ERRORS(NON_FIELD_ERRORS,"__all__") unless the error itself wraps a{field_name: message}dict. - Stage 3 —
BaseForm: A no-op on plain._post_clean Form, overridden byBaseModelFormto copy._post_clean "cleaned_data"onto"self.instance"and run model validation, uniqueness checks, and constraint checks.
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:
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 ("self), 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 inside clean(), because if "headline" failed Stage 1 it is no longer in the dictionary! Always use "cleaned (just as "StoryForm uses "cleaned and "cleaned).
Watch both Stage 1 ("clean_headline" rejecting "ALL CAPS ALERT" and deleting "headline" from "cleaned_data") and Stage 2 ("StoryForm catching City Hall reporter "Cora" assigned to "Metro" under "__all__") fire in the same full_clean run on "desk/":
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):
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.