---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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` (`django/forms/forms.py:BaseForm.is_valid`) is a one-liner: `"return self.is_bound and not self.errors"`. Accessing `BaseForm.errors` (`django/forms/forms.py:BaseForm.errors`) checks `if self._errors is None:` and triggers **`full_clean`** (`django/forms/forms.py:BaseForm.full_clean`) exactly once, caching the resulting `ErrorDict` (`django/forms/utils.py: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` (`django/forms/forms.py:BaseForm._clean_fields`):** Iterates every `(name, bf)` pair from `_bound_items()` in field order. First it calls `Field._clean_bound_field` -> `Field.clean` (`django/forms/fields.py: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` (`django/forms/forms.py:BaseForm._clean_form`):** Runs `BaseForm.clean` (`django/forms/forms.py: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`** (`django/core/exceptions.py:ValidationError`) raised directly from `clean()` is passed to `BaseForm.add_error(None, e)`, attaching it under `NON_FIELD_ERRORS` (`django/core/exceptions.py:NON_FIELD_ERRORS`, `"__all__"`) unless the error itself wraps a `{field_name: message}` dict.
3. **Stage 3 — `BaseForm._post_clean` (`django/forms/forms.py: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.

```text figure=form-validation-pipeline
Three-stage BaseForm.full_clean() pipeline & measured form validation cost (Django 6.1.3, 7 trials)

1. BaseForm.full_clean() -> _clean_fields() -> _clean_form() -> _post_clean():
   Stage 1 (_clean_fields): to_python -> validate -> run_validators -> clean_<field>()
                            ValidationError -> add_error() DELETES key from cleaned_data!
   Stage 2 (_clean_form):   self.clean() cross-field checks -> error attached to '__all__'
   Stage 3 (_post_clean):   ModelForm hook: construct_instance() mutates self.instance EVEN IF INVALID!

2. Form instantiation & validation cost (7 trials, median us):
   PlainForm()  [unbound]      16.2 us  (  1.00x)
   PlainForm.is_valid()        37.9 us  (  2.33x)
   StoryForm()  [7 fields]    120.0 us  (  7.39x)
   FormSet(10).is_valid()     565.1 us  ( 34.81x)
   StoryForm.is_valid() [DB] 1950.2 us  (120.14x — ModelChoiceFields + validate_unique)
```

*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 `ModelChoiceField`s 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` (`django/forms/forms.py:BaseForm.add_error`):

```python
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/"`:

```text recording=ch10-presentation
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`):

```text recording=ch10-bench
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` (`django/forms/fields.py: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](model-forms.md).
