11.7 Sessions, auth, and the admin
changeform_view, inlines, and audit logging
How does ModelAdmin coordinate a parent ModelForm, multiple BaseInlineFormSets, django, and LogEntry inside one POST?
Every time an editor edits a "Story" and adds a "Correction" row on "/, Django executes one of the cleanest orchestrations in the entire framework. Open ModelAdmin and ModelAdmin: every abstraction from Chapters 9 and 10 (django, BaseModelForm with "commit=False", BaseInlineFormSet, and ManagementForm) snaps together in one 100-line method.
Transaction boundaries and validation order
First look at ModelAdmin:
if request.method in ("GET", "HEAD", "OPTIONS", "TRACE"):
return self._changeform_view(request, object_id, form_url, extra_context)
with transaction.atomic(using=router.db_for_write(self.model)):
return self._changeform_view(request, object_id, form_url, extra_context)
Safe read requests skip the transaction wrapper completely; every "POST" runs inside django on the model’s write database! That guarantees atomicity across the parent row, every inline child row, any many-to-many join tables, and the LogEntry audit row — if a custom save_model or inline post_save signal raises an error, the entire edit rolls back cleanly.
Now trace the "POST" branch of ModelAdmin step by step:
- Permission & object check: Loads
"obj = self(or redirects with a warning message if another editor already deleted it!) and verifies.get_object(...)" has_add_permissionorhas_change_permission, raisingPermissionDeniedif unauthorized. - Build parent
ModelFormand inline formsets: CallsModelAdminto synthesize a.get_form ModelFormfor"Story", binds"form = ModelForm(request, and calls.POST, request .FILES, instance=obj)" ModelAdminto construct one._create_formsets BaseInlineFormSetperInlineModelAdminin"StoryAdmin(.inlines" "StoryBeatInline"with prefix"story_beats","CorrectionInline"with prefix"corrections"), anchored to"form.instance". - Validate BOTH parent and all inlines before refusing: Look closely at lines 2146–2151 of
django/:contrib/ admin/ options .py
form_validated = form.is_valid()
if form_validated:
new_object = self.save_form(request, form, change=not add)
else:
new_object = form.instance
if all_valid(formsets) and form_validated:
Notice the deliberate operand order: all_valid(formsets) comes before "form_validated"! Because Python short-circuits and, putting all_valid(formsets) on the left forces Django to validate every inline formset even when the parent form has errors, so the editor sees parent and inline error messages together on a single round trip! And notice ModelAdmin calls "form — deferring the database "INSERT"/"UPDATE" until all inlines pass validation too!
Save order and structured JSON LogEntry auditing
Only when both parent and every inline are valid does Django touch the database — in a strict three-step write order:
ModelAdmin: Saves the parent object (.save_model "obj.save()"), guaranteeing"new_object.pk"exists for foreign keys and many-to-many join rows (UPDATE newsroom_storyon edits).ModelAdmin: Calls.save_related "form(the dynamically bound method we uncovered in Chapter 10!) and then calls.save_m2m()" ModelAdmin(.save_formset "formset.save()") on every inline formset (INSERT INTO newsroom_correction), persisting added, changed, and deleted child rows. Note the famous Admin hook mistake: never inspect a model’s many-to-many relations or inline children insidesave_model— they have not been written yet! Always overridesave_relatedinstead.construct_change_message&LogEntry: CallsModelAdmin, inspecting.construct_change_message "formand each inline formset’s.changed_data" "new_objects","changed_objects", and"deleted_objects"to assemble a structured JSON list (soLogEntrycan later render translated history entries in any language!). Then.get_change_message ModelAdmincalls.log_change LogEntryManagerto insert one row into.log_actions "django_admin_log"(usingContentTypeManagerfrom section 11.4!). Finally,._cache ModelAdminflashes a success message via.response_change djangoand returns a.contrib .messages 302redirect (honoring Post/Redirect/Get and preserving active changelist filters via"_changelist_filters"!).
Watch a live Admin "POST" on "desk/" update "bridge-bond-passes"'s headline and insert a third "Correction" row inside one django block — capturing the exact SQL write order and the resulting LogEntry JSON payload:
7. ModelAdmin._changeform_view atomic POST, inlines, and LogEntry
changeform_post: status=302 redirect='/admin/newsroom/story/' sql=26 corrections_after=3
atomic_write_order = ['BEGIN', 'UPDATE newsroom_story', 'INSERT newsroom_correction', 'INSERT django_admin_log']
log_entry: action_flag=2 (CHANGE) object_repr='Bridge bond clears council on 6-3 vote'
change_message_json = [{"changed": {"fields": ["Headline"]}}, {"added": {"name": "correction", "object": "Correction #4 on bridge-bond-passes"}}]
change_message_text = 'Changed Headline. Added correction “Correction #4 on bridge-bond-passes”.'
Look at "atomic_write_order": "BEGIN" → "UPDATE newsroom_story" → "INSERT newsroom_correction" → "INSERT django_admin_log", followed by "COMMIT" and HTTP 302 back to "/ — every layer of Django working in lockstep!
Beyond auth and the Admin, real apps lean on Django’s built-in horizontal services — caching, signals, Django 6’s native django.tasks framework, file storage, and localisation — each carrying its own subtle traps. We open all five next in Caching, signals, tasks, and files.