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

# ModelForm, _post_clean, and save

How does `ModelFormMetaclass` derive form fields from a model's `_meta`, and why does `BaseModelForm._post_clean` mutate `BaseModelForm.instance` even when the form turns out invalid?

A `ModelForm` (`django/forms/models.py:ModelForm`) looks like a thin wrapper around `Form` that saves typing seven field declarations. Under the hood, it couples two completely different systems — `django/forms/` and `django/db/models/` — across three subtle seams: class creation (`ModelFormMetaclass`), Stage 3 validation (`BaseModelForm._post_clean`), and two-phase persistence (`BaseModelForm.save` and `save_m2m`).

## `ModelFormMetaclass` and `fields_for_model`

**`ModelFormMetaclass`** (`django/forms/models.py:ModelFormMetaclass`) subclasses `DeclarativeFieldsMetaclass` (`django/forms/forms.py:DeclarativeFieldsMetaclass`). First it runs `super().__new__` to collect any explicitly declared fields on the form class. Next it wraps `class Meta:` into a `ModelFormOptions` (`django/forms/models.py:ModelFormOptions`) object — refusing any `ModelForm` that omits *both* `"fields"` and `"exclude"` (`ImproperlyConfigured`, preventing accidental mass-assignment vulnerabilities when a model later gains sensitive columns like `"is_staff"`!).

Then `ModelFormMetaclass` calls `fields_for_model` (`django/forms/models.py:fields_for_model`), which walks `"opts.concrete_fields"`, `"opts.private_fields"`, and `"opts.many_to_many"` on the target model:

- Any non-editable model field (`"editable=False"`, such as `"BigAutoField"` primary keys or `auto_now_add` timestamps) is skipped — or raises `FieldError` if explicitly listed in `"Meta.fields"`.
- For every remaining included model field, Django calls `Field.formfield` (`django/db/models/fields/__init__.py:Field.formfield`) (or `"Meta.formfield_callback"` if provided), turning a model `CharField` into a form `CharField`, a `ForeignKey` into a `ModelChoiceField`, and a `ManyToManyField` into a `ModelMultipleChoiceField`.
- Crucially, `ModelFormMetaclass` passes `"apply_limit_choices_to=False"` at import time; `BaseModelForm.__init__` (`django/forms/models.py:BaseModelForm.__init__`) defers `apply_limit_choices_to_to_formfield` until *instantiation time* so dynamic `"limit_choices_to"` callables evaluate fresh on every request!

## The `BaseModelForm._post_clean` mutation trap (and the `super().clean()` footgun)

Now open `BaseModelForm._post_clean` (`django/forms/models.py:BaseModelForm._post_clean`). This 35-line method is responsible for two of the sharpest surprises in Django:

1. **Unconditional in-memory mutation of `"self.instance"`:** Even if `"self._errors"` already contains errors — OR if `validate_unique()` is about to fail three lines later — `_post_clean` calls `construct_instance` (`django/forms/models.py:construct_instance`), which copies every valid key from `"cleaned_data"` directly onto **`"self.instance"`** via `"f.save_form_data(instance, cleaned_data[f.name])"`! Why? Because `Model.full_clean`, `Model.validate_unique`, and `Model.validate_constraints` inspect attributes on the *model instance*, not on a dictionary! So if a view binds `"StoryForm(request.POST, instance=story)"`, calls `"form.is_valid()"` (which returns **`False`** because `"slug"` duplicates another story), and then renders `"{{ story.headline }}"` in the template or reuses `"story"` later in the view, **`"story.headline"` in Python memory has already been overwritten with the invalid submission's headline** (even though the database row was never touched)!
2. **Forgetting `super().clean()` disables uniqueness and constraint checks:** Look at `BaseModelForm.__init__` and `BaseModelForm.clean` (`django/forms/models.py:BaseModelForm.clean`): `"self._validate_unique"` and `"self._validate_constraints"` both start as **`False`** and are only flipped to `True` inside `BaseModelForm.clean`! If you override `def clean(self):` on a `ModelForm` and return `"self.cleaned_data"` without calling `super().clean()`, `_post_clean` silently skips *both* `validate_unique()` and `validate_constraints()` — letting duplicate values crash with an unhandled `IntegrityError` in `"form.save()"` instead of showing clean form errors!

Notice also `BaseModelForm._get_validation_exclusions` (`django/forms/models.py:BaseModelForm._get_validation_exclusions`): any model field omitted from `"Meta.fields"`, already present in `"self._errors"`, or optional on the form is excluded from `"instance.full_clean(exclude=exclude)"` so Django neither double-reports form errors nor complains about server-populated fields (like `"author"` or `"edition"`) that the view will attach after validation.

## Why `save(commit=False)` creates `save_m2m` dynamically

Look at `BaseModelForm.save` (`django/forms/models.py:BaseModelForm.save`). First it refuses to run if `"self.errors"` is non-empty (`ValueError`). Then it splits cleanly on `"commit"`:

- When `"commit=True"` (the default), it calls `"self.instance.save()"` followed immediately by `BaseModelForm._save_m2m` (`django/forms/models.py:BaseModelForm._save_m2m`), writing every included `ManyToManyField` after the row has a primary key.
- When `"commit=False"`, Django cannot write many-to-many rows yet because an unsaved `"Story"` has `"pk = None"` (`_state.adding = True`), so a foreign key in the join table would fail! Instead, line 579 dynamically binds **`save_m2m`** onto the form instance (`self.save_m2m = self._save_m2m`) and returns the unsaved `"self.instance"` so your view can attach extra fields (`story.reporter = request.user.reporter_profile`), call `"story.save()"`, and then invoke `"form.save_m2m()"` to flush any many-to-many selections!

Watch both the `_post_clean` in-memory mutation trap on `"desk/"`'s `"bridge-bond-passes"` and `"save(commit=False)"` dynamically attaching `"save_m2m"` execute live:

```text recording=ch10-presentation
6. ModelForm._post_clean instance mutation trap and save(commit=False)
  unique_fail: is_valid=False errors=['slug']
  instance_mutated_despite_invalid: before='Bridge bond passes council' after_is_valid='Mutated Headline In Memory' db_still='Bridge bond passes council'
  save(commit=False): pk=None adding=True has_save_m2m_before=False has_save_m2m_after=True
```

Look at line 42: `"is_valid"` returned `False`, the database still holds `'Bridge bond passes council'`, yet `"s1.headline"` in memory was already mutated to `'Mutated Headline In Memory'`! If your view needs the untouched instance after an invalid `ModelForm` submission, either re-fetch it or pass a fresh copy.

One `ModelForm` handles a single object. Editing a `"Story"` together with all of its `"Correction"` rows in one HTTP `"POST"` — the exact machinery powering Django Admin inlines — requires coordinating *multiple* forms inside one flat key-value payload. We finish Chapter 10 with formsets in [Formsets and management form integrity](formsets.md).
