Django 6.1.3

10.6 Templates and forms

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 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 subclasses DeclarativeFieldsMetaclass. First it runs super().__new__ to collect any explicitly declared fields on the form class. Next it wraps class Meta: into a 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, which walks "opts.concrete_fields", "opts.private_fields", and "opts.many_to_many" on the target model:

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

Now open 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, 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: "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: 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. First it refuses to run if "self.errors" is non-empty (ValueError). Then it splits cleanly on "commit":

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:

Recorded on Django 6.1.3 ch10-presentation script
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.