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

# changeform_view, inlines, and audit logging

How does `ModelAdmin._changeform_view` coordinate a parent `ModelForm`, multiple `BaseInlineFormSet`s, `django.db.transaction.atomic`, and `LogEntry` inside one POST?

Every time an editor edits a `"Story"` and adds a `"Correction"` row on `"/admin/newsroom/story/1/change/"`, Django executes one of the cleanest orchestrations in the entire framework. Open `ModelAdmin.changeform_view` (`django/contrib/admin/options.py:ModelAdmin.changeform_view`) and **`ModelAdmin._changeform_view`** (`django/contrib/admin/options.py:ModelAdmin._changeform_view`): every abstraction from Chapters 9 and 10 (`django.db.transaction.atomic`, `BaseModelForm.save` with `"commit=False"`, `BaseInlineFormSet`, and `ManagementForm`) snaps together in one 100-line method.

## Transaction boundaries and validation order

First look at `ModelAdmin.changeform_view`:

```python
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.db.transaction.atomic`** (`django/db/transaction.py:atomic`) 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._changeform_view` step by step:

1. **Permission & object check:** Loads `"obj = self.get_object(...)"` (or redirects with a warning message if another editor already deleted it!) and verifies `has_add_permission` or `has_change_permission`, raising `PermissionDenied` if unauthorized.
2. **Build parent `ModelForm` and inline formsets:** Calls `ModelAdmin.get_form` to synthesize a `ModelForm` for `"Story"`, binds `"form = ModelForm(request.POST, request.FILES, instance=obj)"`, and calls `ModelAdmin._create_formsets` (`django/contrib/admin/options.py:ModelAdmin._create_formsets`) to construct one `BaseInlineFormSet` per **`InlineModelAdmin`** (`django/contrib/admin/options.py:InlineModelAdmin`) in `"StoryAdmin.inlines"` (`"StoryBeatInline"` with prefix `"story_beats"`, `"CorrectionInline"` with prefix `"corrections"`), anchored to `"form.instance"`.
3. **Validate BOTH parent and all inlines before refusing:** Look closely at lines 2146–2151 of `django/contrib/admin/options.py`:

```python
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.save_form` (`django/contrib/admin/options.py:ModelAdmin.save_form`) calls `"form.save(commit=False)"` — 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:

1. **`ModelAdmin.save_model` (`django/contrib/admin/options.py:ModelAdmin.save_model`):** Saves the parent object (`"obj.save()"`), guaranteeing `"new_object.pk"` exists for foreign keys and many-to-many join rows (`UPDATE newsroom_story` on edits).
2. **`ModelAdmin.save_related` (`django/contrib/admin/options.py:ModelAdmin.save_related`):** Calls `"form.save_m2m()"` (the dynamically bound method we uncovered in Chapter 10!) and then calls `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 inside `save_model`** — they have not been written yet! Always override `save_related` instead.
3. **`construct_change_message` & `LogEntry` (`django/contrib/admin/models.py:LogEntry`):** Calls `ModelAdmin.construct_change_message` (`django/contrib/admin/options.py:ModelAdmin.construct_change_message`), inspecting `"form.changed_data"` and each inline formset's `"new_objects"`, `"changed_objects"`, and `"deleted_objects"` to assemble a structured JSON list (so `LogEntry.get_change_message` can later render translated history entries in any language!). Then `ModelAdmin.log_change` (`django/contrib/admin/options.py:ModelAdmin.log_change`) calls `LogEntryManager.log_actions` (`django/contrib/admin/models.py:LogEntryManager.log_actions`) to insert one row into `"django_admin_log"` (using `ContentTypeManager._cache` from section 11.4!). Finally, `ModelAdmin.response_change` flashes a success message via `django.contrib.messages` and returns a `302` redirect (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.db.transaction.atomic` block — capturing the exact SQL write order and the resulting `LogEntry` JSON payload:

```text recording=ch11-auth
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 `"/admin/newsroom/story/"` — 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](../services.md).
