Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 77 ยท Forms

ModelForms

Build Django forms straight from models with ModelForm, customize fields and widgets, use save(commit=False), and edit related rows with inline formsets.

Most forms in a Django project exist to create or edit a database row. If you wrote a plain form for each of them, you would repeat every field twice: once in the model and once in the form, including lengths, required flags and choices. Change one and forget the other, and you have a bug.

A ModelForm removes that duplication. You name a model, list the fields you want, and Django builds the form fields from the model fields, copies their validation rules, and gives you a save() method that writes to the database. You can still customize anything. In this lesson you will build ModelForms, control which fields appear, use save(commit=False) for the cases where the form is not the whole story, and edit a parent row together with its children using inline formsets.

A ModelForm needs a model, and a model needs a Django app. The examples on this page register a tiny stand-in package called blog (the thing startapp would create for you) so that relations between models work inside the browser. In a real project you simply write the model in your app's models.py.

From model to form

flowchart LR
    M["Model<br/>fields + validation"] -->|"Meta.model and Meta.fields"| F["ModelForm<br/>form fields built for you"]
    F -->|"is_valid()"| V["Validated data"]
    V -->|"save()"| DB[("Database row")]
    DB -.->|"instance=..."| F

A ModelForm is generated from a model, validates like a normal form, and saves to the database. Passing instance= makes it edit an existing row.

The Meta inner class tells Django which model to use and which fields to include. Every model field type has a matching form field: CharField becomes a text input, BooleanField a checkbox, ManyToManyField a multiple-select that lists existing rows, and so on. Rules such as max_length carry over, and fields marked blank=True become optional.

Python A ModelForm that creates and updates rows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Several details are worth studying in that output:

  • Only listed fields appear. views is not in fields, so users cannot set it. This is an important security habit: explicitly list the fields a form may change. The shortcut fields = "__all__" includes every editable model field and silently exposes new fields you add later. exclude = [...] has the same trap; prefer an explicit list.
  • labels, help_texts, widgets and error_messages in Meta customize individual fields without redeclaring them.
  • Many-to-many data arrives as primary keys, and form.save() also saves the many-to-many relations for you.
  • Passing instance=post makes the form edit that row instead of creating one. The form is pre-filled from the instance when unbound.
  • Look at the update: the data had no published key, because an unchecked browser checkbox sends nothing, so the form set published to False. A real browser submits every field of the page, so this is correct there. If you build the data yourself (in a test, say), include every field or you will clear some by accident.
  • You can declare extra fields (for example confirm = forms.BooleanField()) on a ModelForm like on any form. They validate but are not saved to the model.

For one-off forms you can also skip the class and call forms.modelform_factory(Post, fields=["title"]).

save(commit=False)

form.save() creates the object and writes it to the database in one step. Often the form does not know everything that belongs in the row. The author comes from request.user, a slug is computed, a status is set by the system. For those cases call save(commit=False): it builds the model instance from the form data without writing it, so you can set the remaining attributes first.

Python save(commit=False) and save_m2m()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three points to remember:

  1. With commit=False the object has no primary key yet (pk is None). Set the extra attributes, call article.save() yourself, and
  2. call form.save_m2m() afterwards when the form has many-to-many fields. Django cannot link rows that do not exist yet, and commit=False skips that step. Forgetting this call is a classic bug: the article saves but its labels silently disappear.
  3. unique=True on a model field produces a form error (code: unique) instead of an IntegrityError, because ModelForm validation also checks uniqueness. It is a nice message for the user, but it is still not a lock: two simultaneous requests can both pass the check, so the database constraint remains the real guard.

Formsets: many forms on one page

Sometimes you must edit several rows at once: the ingredients of a recipe, the lines of an invoice. A formset is a collection of forms of the same kind, managed together. A hidden management form (TOTAL_FORMS, INITIAL_FORMS and friends) tells Django how many forms were sent.

  • modelformset_factory(Model, fields=[...]) makes a formset that edits rows of one model.
  • inlineformset_factory(Parent, Child, fields=[...]) edits the children of one parent and sets the foreign key automatically. It is the usual tool for "one recipe, many ingredients".
Python An inline formset for recipe ingredients

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Key observations:

  • The prefix ingredients- comes from the related_name, so each field is called ingredients-0-name, ingredients-1-name and so on. The hidden id and DELETE fields appear automatically when needed.
  • Blank extra forms are ignored: a form the user did not touch is skipped, so you can show spare empty rows without forcing the user to fill them. (This works only if the form has no initial values that differ from the empty submission. A model field with default=0, for example, makes an untouched form look "changed", which is why this example has no default on grams.)
  • A row that is partially filled gets its own errors; the rest of the formset is unaffected. formset.is_valid() is True only when every form is valid.
  • can_delete=True adds a checkbox per existing row. Rows whose DELETE is set are deleted by formset.save().
  • In a template you render {{ formset.management_form }} and loop over {{ formset }} or formset.forms. Without the management form the formset is invalid and reports that the ManagementForm data is missing. This is the most common formset mistake.

When a parent and its children are edited in one page, validate and save them together inside a transaction: check both form.is_valid() and formset.is_valid(), and call save() for the parent first, then the formset. If one of them fails, nothing should be written.

When not to use a ModelForm

A ModelForm is perfect when the form mirrors one model. When the form touches several models, collects values that become a calculation, or must not expose the model's shape (a search form, a payment form, a "contact us" message), use a plain Form. Likewise, for an API that accepts JSON, serializers or plain validation code are often a better fit than HTML-oriented forms.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which Meta option should you use to decide which model fields a ModelForm exposes?

    An explicit list means that a field added to the model later is not exposed to users by accident. __all__ and exclude include new fields automatically.
  2. 2. You call article = form.save(commit=False). What is true afterwards?

    commit=False builds the instance but does not write it. You set extra attributes, save it, and then call form.save_m2m() if the form has many-to-many fields.
  3. 3. Why is form.save_m2m() needed after save(commit=False)?

    Linking rows in the through table requires the instance to exist in the database. With commit=False Django postpones that step until you call save_m2m().
  4. 4. What makes ModelForm(data, instance=post) different from ModelForm(data)?

    With an instance the form edits that object and save() runs an UPDATE. Without it, save() inserts a new row.
  5. 5. What must you include in a template so an inline formset can be submitted and validated?

    The management form carries TOTAL_FORMS, INITIAL_FORMS and related counters. Without them Django cannot tell how many forms were submitted and reports an error.

Summary

  • A ModelForm generates form fields and validation from a model; set Meta.model and Meta.fields.
  • Always list fields explicitly; avoid "__all__" and exclude for forms that users can submit.
  • Customize with labels, help_texts, widgets, error_messages or by declaring fields on the form.
  • form.save() inserts or updates (with instance=) and saves many-to-many data.
  • Use save(commit=False) to fill in values the user does not type, then save the object and call save_m2m().
  • Model rules such as unique=True and max_length appear as form errors.
  • Formsets edit several rows together; inline formsets edit the children of one parent, and the management form is required.

Next, see how forms fit into the request cycle in Handling Forms in Views.