ModelForm, _post_clean, and save
How does ModelFormMetaclass derive form fields from a model’s _meta, and why does BaseModelForm mutate BaseModelForm 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/ — across three subtle seams: class creation (ModelFormMetaclass), Stage 3 validation (BaseModelForm), and two-phase persistence (BaseModelForm 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, "opts, and "opts on the target model:
- Any non-editable model field (
"editable=False", such as"BigAutoField"primary keys orauto_now_addtimestamps) is skipped — or raisesFieldErrorif explicitly listed in"Meta.fields". - For every remaining included model field, Django calls
Field.formfield(or"Metaif provided), turning a model.formfield_callback" CharFieldinto a formCharField, aForeignKeyinto aModelChoiceField, and aManyToManyFieldinto aModelMultipleChoiceField. - Crucially,
ModelFormMetaclasspasses"apply_limit_choices_to=False"at import time;BaseModelFormdefers.__init__ apply_limit_choices_to_to_formfielduntil 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. This 35-line method is responsible for two of the sharpest surprises in Django:
- Unconditional in-memory mutation of
"self.instance": Even if"self._errors"already contains errors — OR ifvalidate_unique()is about to fail three lines later —_post_cleancallsconstruct_instance, which copies every valid key from"cleaned_data"directly onto"self.instance"via"f! Why? Because.save_form_data(instance, cleaned_data[f .name])" Model.full_clean,Model, and.validate_unique Modelinspect attributes on the model instance, not on a dictionary! So if a view binds.validate_constraints "StoryForm(request, calls.POST, instance=story)" "form(which returns.is_valid()" Falsebecause"slug"duplicates another story), and then renders"{{ storyin the template or reuses.headline }}" "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)! - Forgetting
super().clean()disables uniqueness and constraint checks: Look atBaseModelFormand.__init__ BaseModelForm:.clean "selfand._validate_unique" "selfboth start as._validate_constraints" Falseand are only flipped toTrueinsideBaseModelForm! If you override.clean def clean(self):on aModelFormand return"selfwithout calling.cleaned_data" super().clean(),_post_cleansilently skips bothvalidate_unique()andvalidate_constraints()— letting duplicate values crash with an unhandledIntegrityErrorin"form.save()"instead of showing clean form errors!
Notice also BaseModelForm: any model field omitted from "Meta.fields", already present in "self._errors", or optional on the form is excluded from "instance 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. 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"selffollowed immediately by.instance .save()" BaseModelForm, writing every included._save_m2m ManyToManyFieldafter 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), so a foreign key in the join table would fail! Instead, line 579 dynamically binds.adding = True save_m2monto the form instance (self) and returns the unsaved.save_m2m = self ._save_m2m "self.instance"so your view can attach extra fields (story), call.reporter = request .user .reporter_profile "story.save()", and then invoke"formto flush any many-to-many selections!.save_m2m()"
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:
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.