Django Model Formsets & Inline Formsets: A Deep Dive

MicroPyramid Updated 15 min read

Clipboard with a parent form above a Formset of child rows, one with DELETE ticked, a plus button adding a ghost row, and a ManagementForm counter

Short answer: a model formset is a group of ModelForms that Django handles as one form, so a single POST can create, edit and delete many rows of one model. Use modelformset_factory() for a flat list of one model, such as an "edit all open tasks" grid, and inlineformset_factory() when the rows belong to one parent object, such as a project and its tasks on one page.

Tested with Django 5.2.19 and Python 3.12.16 on 17 November 2026. Every example below was run on SQLite and exercised through Django's test client (creating, editing, deleting, validation errors and a missing management form), and the add-row JavaScript was clicked through in a browser. The same code also runs on Django 4.2, but 4.2 no longer gets security fixes; our Django 4.2 to 5.2 upgrade guide covers the move.

New to forms in Django? Start with Django forms basics and then come back here.

Plain form vs model formset vs inline formset

  • A plain ModelForm edits exactly one object. Use it for "create one project" or "edit my profile".
  • A model formset (modelformset_factory) edits many objects of the same model at once, such as an admin-style "edit all open tasks" grid. You usually pass it a queryset.
  • An inline formset (inlineformset_factory) edits the objects that point at a parent instance through a ForeignKey. It builds on the model formset: it limits the queryset to that parent's children and sets the foreign key for you on save. Use it for "a project and its tasks on one screen".

Rule of thumb: for a parent and its children on one page, use an inline formset; for a flat list of one model, a model formset; for a single record, a plain form.

A model to work with

We will use a simple parent and child pair: a Project with many Task rows. ForeignKey needs an explicit on_delete (it has been mandatory since Django 2.0). The updated_by field is there for the commit=False example later; none of the forms show it.

# models.py
from django.conf import settings
from django.db import models


class Project(models.Model):
    name = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name


class Task(models.Model):
    project = models.ForeignKey(
        Project, on_delete=models.CASCADE, related_name="tasks"
    )
    title = models.CharField(max_length=200)
    done = models.BooleanField(default=False)
    tags = models.ManyToManyField("Tag", blank=True)
    updated_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name="+",
    )

    def __str__(self):
        return self.title


class Tag(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name

Editing many rows with modelformset_factory

A model formset edits rows of a single model. List the editable fields (or exclude) explicitly: Django refuses to build the factory without one of them, and fields="__all__" or exclude=() quietly exposes every field you add to the model later.

This grid edits and deletes existing tasks but never creates them, because a new Task needs a project and this form does not ask for one. extra=0 only stops Django rendering blank forms. edit_only=True (Django 4.1 and newer) also makes it ignore rows that a hand-crafted POST adds; without it, our test POST with one extra row reached the database and the view failed with a server error.

# forms.py
from django.forms import modelformset_factory
from .models import Task

TaskListFormSet = modelformset_factory(
    Task,
    fields=["title", "done"],
    extra=0,          # no blank forms: this grid only edits existing rows
    edit_only=True,   # ignore new rows, even if a crafted POST adds some
    can_delete=True,  # render a DELETE checkbox per row
)

Instantiate it with a queryset to scope which rows it manages. Anything outside that queryset is untouched. If the queryset has no ordering, Django orders it by primary key, so the rows line up the same way on GET and on POST.

# views.py
from django.shortcuts import render, redirect
from .forms import TaskListFormSet
from .models import Task


def edit_open_tasks(request):
    qs = Task.objects.filter(done=False).order_by("title")
    if request.method == "POST":
        formset = TaskListFormSet(request.POST, queryset=qs)
        if formset.is_valid():
            formset.save()
            return redirect("task-list")
    else:
        formset = TaskListFormSet(queryset=qs)
    return render(request, "tasks/edit.html", {"formset": formset})

Factory options you will actually use

Both factories share most of these keyword arguments:

  • extra: the number of blank forms rendered for new rows (default 1; use 0 for an edit grid).
  • can_delete: adds a DELETE checkbox so existing rows can be removed.
  • can_delete_extra: when False, the blank extra forms get no DELETE box (Django 3.2 and newer).
  • can_order: adds an ORDER field per form; read the rows back in the chosen order from formset.ordered_forms.
  • edit_only: only update or delete existing rows, never create new ones (Django 4.1 and newer).
  • max_num: caps how many forms are rendered. On submit it is enforced only with validate_max=True; without it, our test accepted 25 posted rows with max_num=20.
  • min_num: adds that many forms to the page and makes them required, but a POST that sends fewer rows passes unless you also set validate_min=True.
  • absolute_max: the hard ceiling on how many forms Django builds from one POST, which protects memory. It defaults to max_num + 1000, so 2000 when you leave max_num at its default of 1000.
  • fields / exclude: which model fields appear (one of them is required unless you pass a custom form that defines them).
  • form: a custom ModelForm subclass to control widgets, labels and per-field clean().

The example below accepts new rows, so it puts project in fields. Every required model field has to be on the form or set in the view before saving; otherwise the database rejects the new row.

# forms.py
from django.forms import modelformset_factory
from .models import Task

TaskGridFormSet = modelformset_factory(
    Task,
    fields=["project", "title", "done"],  # new rows need their project
    extra=2,
    max_num=20,
    validate_max=True,        # reject a POST with more than 20 rows
    can_order=True,           # adds an ORDER field per form
    can_delete=True,
    can_delete_extra=False,   # no DELETE box on the blank extras
)

The management form: never forget it

Every formset ships hidden bookkeeping inputs that Django uses to rebuild the set on POST. They live in the management form and carry the formset's prefix (form by default for a model formset):

  • form-TOTAL_FORMS: how many forms were rendered (your JavaScript updates this when adding rows).
  • form-INITIAL_FORMS: how many of them are bound to existing objects.
  • form-MIN_NUM_FORMS / form-MAX_NUM_FORMS: the min and max hints. Django renders them but does not require them in the POST.

{{ formset }} includes the management form automatically; a manual loop does not, so output {{ formset.management_form }} yourself. Without it, Django does not raise an exception (it has not since Django 3.2): is_valid() returns False and the error "ManagementForm data is missing or has been tampered with" goes into formset.non_form_errors(). If your template does not render non_form_errors, the page simply reloads and nothing is saved, which is hard to debug.

When you render the fields one by one, also output {{ form.id }}, the hidden primary key of each row. Without it, every existing row fails with "This field is required" on a field the user cannot see.

{# tasks/edit.html #}
<form method="post">
  {% csrf_token %}
  {{ formset.management_form }}  {# required when you loop over the forms yourself #}
  {{ formset.non_form_errors }}  {# formset-level errors, including a missing management form #}
  {% for form in formset %}
    <div class="row">
      {{ form.id }}  {# hidden primary key: existing rows fail validation without it #}
      {{ form.non_field_errors }}
      {{ form.title.errors }} {{ form.title }}
      <label>{{ form.done }} Done</label>
      {% if formset.can_delete %}<label>{{ form.DELETE }} Delete</label>{% endif %}
    </div>
  {% endfor %}
  <button type="submit">Save</button>
</form>

Saving: save(), commit=False, deletes, and M2M

For a model formset, formset.save() creates new rows, updates changed ones, and (with can_delete=True) deletes the rows whose DELETE box was ticked. When you need to set extra attributes before writing, use commit=False. Then you are responsible for deletes and for any many-to-many data:

  • formset.save(commit=False) returns the new and changed instances without touching the database. Rows the user did not change are not in the list.
  • formset.deleted_objects lists the rows marked for deletion; delete them yourself.
  • formset.save_m2m() writes deferred many-to-many data, such as Task.tags when it is one of the form's fields. Call it after any commit=False save.

The view below needs @login_required: assigning an anonymous user to the updated_by foreign key raises a ValueError.

# views.py: commit=False so we can stamp each row
from django.contrib.auth.decorators import login_required


@login_required
def edit_open_tasks(request):
    qs = Task.objects.filter(done=False).order_by("title")
    if request.method == "POST":
        formset = TaskListFormSet(request.POST, queryset=qs)
        if formset.is_valid():
            instances = formset.save(commit=False)  # new and changed rows, not saved yet
            for obj in instances:
                obj.updated_by = request.user       # a model field the form does not show
                obj.save()
            for obj in formset.deleted_objects:
                obj.delete()                        # with commit=False, deletes are yours
            formset.save_m2m()                      # needed after any commit=False save
            return redirect("task-list")
    else:
        formset = TaskListFormSet(queryset=qs)
    return render(request, "tasks/edit.html", {"formset": formset})

Validation: per-form clean() vs formset clean()

There are two layers of validation:

  1. Per-form validation lives on a custom ModelForm (clean_<field>() / clean()) and checks one row on its own.
  2. Formset-level validation lives in clean() on a subclass of BaseModelFormSet or BaseInlineFormSet, and is where you check rows against each other.

For exact duplicates, a database constraint does most of the work: model formsets compare the submitted rows against unique, unique_together and UniqueConstraint fields and report "Please correct the duplicate data for title." Keep the constraint as the final guard either way. In our tests, an inline formset did not check a UniqueConstraint against existing rows that were not part of the submitted set, so that duplicate only failed in the database. Use the formset clean() for rules a constraint cannot express, such as the case-insensitive check below, where "Design" and "design" count as the same title.

Inside the formset clean(), return early if any(self.errors) so you do not trip over rows that already failed, then skip rows marked for deletion and blank extra rows. Do not skip rows just because form.has_changed() is False: an earlier version of this example did, and our tests showed it let a new row duplicate an existing row the user had not touched. Errors you raise here appear in formset.non_form_errors().

# forms.py
from django.core.exceptions import ValidationError
from django.forms import BaseInlineFormSet, inlineformset_factory
from .models import Project, Task


class BaseTaskFormSet(BaseInlineFormSet):
    def clean(self):
        super().clean()
        if any(self.errors):
            return  # some rows failed on their own; skip the cross-row check
        seen = set()
        for form in self.forms:
            if self.can_delete and self._should_delete_form(form):
                continue  # rows being deleted do not count
            title = form.cleaned_data.get("title")
            if not title:
                continue  # a blank extra row
            key = title.casefold()  # "Design" and "design" count as the same
            if key in seen:
                raise ValidationError("Task titles must be unique within a project.")
            seen.add(key)


TaskFormSet = inlineformset_factory(
    Project,
    Task,
    formset=BaseTaskFormSet,
    fields=["title", "done"],
    extra=1,
    can_delete=True,
)

Inline formsets: a parent plus its children

inlineformset_factory(Project, Task, ...) builds a formset whose forms are Task rows tied to a Project. Bind it to a parent with instance=project: the formset then loads only that project's tasks and sets each task's project on save, so a plain formset.save() is all you need.

Pair it with a normal ModelForm for the parent, and save nothing until both are valid. Reading the parent's fields straight from request.POST skips validation: in our test, a POST without name crashed the view, and a blank name was saved.

An inline formset's default prefix is the reverse accessor name: tasks here, because of related_name="tasks" (it would be task_set without it). Passing prefix="tasks" explicitly keeps the input names (tasks-TOTAL_FORMS and so on) stable for your JavaScript even if the related name changes, and you need distinct prefixes when two formsets share a page.

# forms.py (next to TaskFormSet)
from django import forms


class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = ["name"]


# views.py: one function-based view for creating and editing a project with its tasks
from django.db import transaction
from django.shortcuts import render, redirect, get_object_or_404
from .forms import ProjectForm, TaskFormSet
from .models import Project


def edit_project(request, pk=None):
    project = get_object_or_404(Project, pk=pk) if pk else Project()
    if request.method == "POST":
        form = ProjectForm(request.POST, instance=project)
        formset = TaskFormSet(request.POST, instance=project, prefix="tasks")
        if form.is_valid() and formset.is_valid():
            with transaction.atomic():
                project = form.save()
                formset.save()  # sets each task's project for you
            return redirect("project-detail", pk=project.pk)
    else:
        form = ProjectForm(instance=project)
        formset = TaskFormSet(instance=project, prefix="tasks")
    return render(request, "projects/form.html", {"form": form, "formset": formset})

Rendering an inline formset (and exposing empty_form)

Render the parent form, the management form, the existing and extra rows, and a hidden empty_form prototype. formset.empty_form is a blank form whose field names contain the literal placeholder __prefix__; the JavaScript below swaps it for a real index. Keeping it inside a <template> element means the browser never renders or submits the placeholder fields. The loop variable is task_form, to keep it apart from the parent form.

{# projects/form.html #}
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}  {# the project's own fields #}

  {{ formset.management_form }}
  {{ formset.non_form_errors }}

  <div id="forms-container">
    {% for task_form in formset %}
      <div class="task-form">{{ task_form.as_p }}</div>
    {% endfor %}
  </div>

  {# blank prototype with __prefix__ placeholders; a template element is never submitted #}
  <template id="empty-form-template">
    <div class="task-form">{{ formset.empty_form.as_p }}</div>
  </template>

  <button type="button" id="add-task">Add task</button>
  <button type="submit">Save</button>
</form>

Adding rows dynamically with JavaScript

The __prefix__ trick is the standard way to add rows in the browser: clone the empty_form markup, replace __prefix__ with the next index, append it, and bump TOTAL_FORMS so Django processes the new row. Here it is in plain JavaScript (no framework, no TypeScript), with a check against MAX_NUM_FORMS. Save it as a static file and load it after the form.

// add-task.js: vanilla JavaScript, progressive enhancement
document.getElementById("add-task").addEventListener("click", addTaskForm);

/**
 * Clone the empty_form prototype, replace the __prefix__ placeholder with the
 * next form index, append it to the container, and increment TOTAL_FORMS so
 * Django validates and saves the new row. Stops at MAX_NUM_FORMS.
 * @returns {void}
 */
function addTaskForm() {
  const total = document.getElementById("id_tasks-TOTAL_FORMS");
  const max = parseInt(document.getElementById("id_tasks-MAX_NUM_FORMS").value, 10);
  const index = parseInt(total.value, 10);
  if (index >= max) return;

  const markup = document.getElementById("empty-form-template").innerHTML;
  document
    .getElementById("forms-container")
    .insertAdjacentHTML("beforeend", markup.replaceAll("__prefix__", String(index)));
  total.value = String(index + 1);
}

If you would rather not hand-roll this, a few popular helpers do the same job: django-formset (server-driven widgets and client validation), htmx (fetch a new row fragment from the server and swap it in), and Alpine.js (small reactive sprinkles for show/hide and counters). They are conveniences; the underlying __prefix__ and TOTAL_FORMS contract is the same. For parent, child and grandchild structures, see our walkthrough on nested formsets in Django.

Using formsets with class-based views

Django's generic class-based views handle one form, not a second formset, so the established pattern is to add the formset in get_context_data() and save it in form_valid(). The mixin below does that for both CreateView and UpdateView: self.object is None when creating and the project when updating, so the same code loads the right tasks. It redirects on its own instead of calling super().form_valid(), which would save the project a second time, and it saves the project and its tasks in one transaction. (New to class-based views? See an introduction to Django class-based views.)

# views.py
from django.db import transaction
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy
from django.views.generic import CreateView, UpdateView
from .forms import ProjectForm, TaskFormSet
from .models import Project


class ProjectWithTasksMixin:
    model = Project
    form_class = ProjectForm
    template_name = "projects/form.html"
    success_url = reverse_lazy("project-list")

    def get_formset(self):
        data = self.request.POST if self.request.method == "POST" else None
        # self.object is None when creating and the project when updating
        return TaskFormSet(data, instance=self.object, prefix="tasks")

    def get_context_data(self, **kwargs):
        kwargs.setdefault("formset", self.get_formset())
        return super().get_context_data(**kwargs)

    def form_valid(self, form):
        formset = self.get_formset()
        if not formset.is_valid():
            return self.render_to_response(self.get_context_data(form=form, formset=formset))
        with transaction.atomic():
            self.object = form.save()
            formset.instance = self.object
            formset.save()
        return HttpResponseRedirect(self.get_success_url())


class ProjectCreateView(ProjectWithTasksMixin, CreateView):
    pass


class ProjectUpdateView(ProjectWithTasksMixin, UpdateView):
    pass

Testing formsets

The thing that trips people up in tests is the management form: a POST without TOTAL_FORMS and INITIAL_FORMS fails validation before your rows are ever looked at. MIN_NUM_FORMS and MAX_NUM_FORMS are optional. To edit existing rows in a test, send each row's id (tasks-0-id) and set INITIAL_FORMS to the number of existing rows.

To check formset errors, pass the formset itself to assertFormSetError(), with None as the form index and the field for errors raised in the formset's clean(). The older assertFormsetError() spelling and the signature that took a response were removed in Django 5.1 and 5.0, so tests written for older versions need this change. For more on testing forms and views, see Django unit test cases with forms and views.

# tests.py
from django.test import TestCase
from django.urls import reverse
from .models import Project, Task


class ProjectFormSetTests(TestCase):
    def test_create_project_with_tasks(self):
        data = {
            "name": "Launch",
            # management form: TOTAL_FORMS and INITIAL_FORMS are required
            "tasks-TOTAL_FORMS": "2",
            "tasks-INITIAL_FORMS": "0",
            # the rows
            "tasks-0-title": "Design",
            "tasks-0-done": "on",
            "tasks-1-title": "Build",
        }
        response = self.client.post(reverse("project-create"), data)

        self.assertRedirects(response, reverse("project-list"), fetch_redirect_response=False)
        self.assertEqual(Task.objects.filter(project__name="Launch").count(), 2)

    def test_duplicate_titles_are_rejected(self):
        data = {
            "name": "Launch",
            "tasks-TOTAL_FORMS": "2",
            "tasks-INITIAL_FORMS": "0",
            "tasks-0-title": "Design",
            "tasks-1-title": "design",
        }
        response = self.client.post(reverse("project-create"), data)

        self.assertEqual(response.status_code, 200)  # the page is shown again with errors
        self.assertFormSetError(
            response.context["formset"], None, None,
            "Task titles must be unique within a project.",
        )
        self.assertFalse(Project.objects.exists())

Wrapping up

Model and inline formsets remove a lot of boilerplate from "edit many rows" and "parent and children" screens. Keep these in mind: render the management form and each row's hidden id, list fields explicitly, use edit_only=True for grids that must not create rows, validate the parent form and the formset before saving either, choose commit=False only when you need extra control (then handle deleted_objects and save_m2m()), do cross-row checks in the formset clean(), and use empty_form with __prefix__ for dynamic rows. If you would like a hand designing complex multi-model forms or modernizing an older Django app, our Django development services team can help.

Frequently Asked Questions

What is the difference between a model formset and an inline formset?

A model formset (modelformset_factory) edits many rows of one model and is usually given a queryset. An inline formset (inlineformset_factory) is a model formset tied to a parent object through a ForeignKey: it limits the rows to that parent's children and sets the foreign key on save. Use inline formsets for "parent and children on one page".

Why do I get "ManagementForm data is missing or has been tampered with"?

Your POST does not contain the management form fields (<prefix>-TOTAL_FORMS and <prefix>-INITIAL_FORMS). This happens when you loop over the forms by hand and forget {{ formset.management_form }}, when a test or AJAX payload leaves those keys out, or when the prefix in the POST does not match the formset's prefix. Since Django 3.2 this is not an exception: the formset is invalid and the message is in formset.non_form_errors(), so render that in your template to see it.

When should I use save(commit=False) with a formset?

Use it when you need to set attributes that are not form fields (an owner, a timestamp, a tenant), or when you must control the order of writes. After a commit=False save you must save the returned instances yourself, delete formset.deleted_objects, and call formset.save_m2m() to persist many-to-many data.

How do I validate uniqueness or relationships across all the forms?

For exact duplicates, add a UniqueConstraint or unique_together to the model: model formsets check the submitted rows against each other for you, and the database stays the final guard. For other rules, subclass BaseModelFormSet or BaseInlineFormSet and override clean(). Return early if any(self.errors), skip rows marked for deletion and blank extra rows, then compare values across self.forms. Raise ValidationError; the message appears in formset.non_form_errors().

How do I add formset rows dynamically without a JavaScript framework?

Render {{ formset.empty_form }} inside a <template> element. In JavaScript, read TOTAL_FORMS, clone the template markup, replace the literal __prefix__ with the current count, append it, and increment TOTAL_FORMS. Helpers like django-formset, htmx or Alpine.js automate this but use the same contract.

How many forms can a formset handle, and how do I cap it?

Control what is rendered with extra, max_num and min_num. To enforce the limits on submit, also pass validate_max=True and validate_min=True; otherwise a POST can send more or fewer rows. Separately, Django rejects a POST with more than absolute_max forms and never builds more than that many. It defaults to max_num + 1000, which is 2000 when max_num stays at its default of 1000; pass absolute_max to lower it.

How do I stop a model formset from creating new objects?

Pass edit_only=True to modelformset_factory() or inlineformset_factory() (Django 4.1 and newer). Setting extra=0 only stops blank forms being rendered; a POST that raises TOTAL_FORMS can still add rows unless edit_only is set.

Share this article
Facebook X LinkedIn
Related serviceDjango Development Services

Start with a discovery call.

  1. TODAY Send a short message Tell us what you run and where it hurts.
  2. WITHIN ONE WORKING DAY We reply From the engineers you would work with, to set up a free 30-minute call.
  3. ON THE CALL Your first step A fixed-scope sprint or audit. Monthly maintenance after it only if you want it.
Talk to an engineer
Email
hello@micropyramid.com
Offices
Plano --:--Hyderabad --:--Sharjah --:--
You own
All code & IP, from day one

We reply within one working day