TExcelTAD
Home › Django › Django ModelForms

Django ModelForms

Most forms on a database-driven site create or edit a model instance: a "new book" form, an "edit profile" form. Declaring every field twice — once on the model, once on the form — would be repetitive and error-prone. A ModelForm builds its fields from a model automatically, validates them using the model's rules, and can save() the result straight to the database.

python
from django import forms
from .models import Book

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ["title", "author", "pages"]
Meta option Purpose
model the model the form is based on
fields list of fields to include (or "__all__")
exclude fields to leave out (use fields instead when you can)
labels, help_texts override labels / help texts per field
widgets override widgets per field
error_messages custom messages per field and error code

Tip: Always list fields explicitly. With "__all__", a field you add to the model later (say, is_admin) silently becomes editable by users.

Fields generated from the model

python · try it yourself
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django import forms
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    pages = models.PositiveIntegerField(help_text="Total number of pages")
    format = models.CharField(max_length=2, choices=[("PB", "Paperback"), ("HC", "Hardcover")])
    summary = models.TextField(blank=True)
    class Meta:
        app_label = "demo"

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ["title", "pages", "format", "summary"]
        labels = {"title": "Book title"}

form = BookForm()
for name, field in form.fields.items():
    print(f"{name:<8} {type(field).__name__:<17} required={field.required} label={field.label!r}")
print(form.fields["pages"].help_text)
title    CharField         required=True label='Book title'
pages    IntegerField      required=True label='Pages'
format   TypedChoiceField  required=True label='Format'
summary  CharField         required=False label='Summary'
Total number of pages

blank=True on the model made summary optional; choices turned into a select box; max_length and PositiveIntegerField's minimum value become validators.

Creating objects with save()

form.save() creates a new row from cleaned_data and returns the instance:

python · try it yourself
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django import forms
from django.db import models, connection

class Book(models.Model):
    title = models.CharField(max_length=100, unique=True)
    pages = models.PositiveIntegerField()
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Book)

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ["title", "pages"]

form = BookForm({"title": "Siddhartha", "pages": "152"})
if form.is_valid():
    book = form.save()
    print("saved:", book.pk, book.title, book.pages)

duplicate = BookForm({"title": "Siddhartha", "pages": "-5"})
print(duplicate.is_valid())
for field, errors in duplicate.errors.items():
    print(f"  {field}: {errors[0]}")
print(Book.objects.count(), "book(s)")
saved: 1 Siddhartha 152
False
  pages: Ensure this value is greater than or equal to 0.
  title: Book with this Title already exists.
1 book(s)

ModelForm validation includes the model's own constraints — like unique=True — which it checks with a database query.

Editing existing objects with instance=

Pass instance= to edit an existing object. Unbound, the form shows the object's current values; bound, save() updates that row instead of creating a new one:

python · try it yourself
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django import forms
from django.db import models, connection

class Book(models.Model):
    title = models.CharField(max_length=100)
    pages = models.PositiveIntegerField()
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Book)
book = Book.objects.create(title="The Hobit", pages=310)

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ["title", "pages"]

edit = BookForm(instance=book)
print("initial:", edit["title"].value(), edit["pages"].value())

edit = BookForm({"title": "The Hobbit", "pages": "310"}, instance=book)
print("changed:", edit.has_changed(), edit.changed_data)
edit.save()
print(list(Book.objects.values_list("id", "title")))
initial: The Hobit 310
changed: True ['title']
[(1, 'The Hobbit')]

save(commit=False): fill in extra fields

Sometimes the form doesn't contain every field: the owner should be the logged-in user, a slug is computed, and so on. save(commit=False) returns an unsaved instance so you can set those fields before saving it yourself:

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
                   DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django import forms
from django.db import models, connection
from django.http import HttpResponse
from django.urls import path
from django.utils.text import slugify
from django.test import Client

class Post(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    slug = models.SlugField()
    author = models.CharField(max_length=30)
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Post)

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ["title", "body"]          # slug and author are NOT user-editable

def new_post(request):
    form = PostForm(request.POST)
    if not form.is_valid():
        return HttpResponse(str(form.errors.as_data()), status=400)
    post = form.save(commit=False)          # not in the database yet
    post.slug = slugify(post.title)
    post.author = request.headers.get("X-User", "anonymous")
    post.save()
    return HttpResponse(f"created #{post.pk}: /{post.slug}/ by {post.author}", status=201)

urls.urlpatterns = [path("posts/new/", new_post)]

c = Client()
r = c.post("/posts/new/", {"title": "Hello Django World", "body": "First!", "author": "hacker"},
           headers={"X-User": "nhi"})
print(r.status_code, r.content.decode())
print(Post.objects.values("title", "slug", "author").get())
201 created #1: /hello-django-world/ by nhi
{'title': 'Hello Django World', 'slug': 'hello-django-world', 'author': 'nhi'}

The sneaky "author": "hacker" in the POST data was ignored, because author isn't in the form's fields. (In a real app you'd use request.user; here a header stands in for the logged-in user.)

Note: If the model has many-to-many fields and you use commit=False, call form.save_m2m() after saving the instance.

Test yourself

What does a ModelForm's Meta.fields control?

  1. Which database columns exist
  2. Which model fields appear in (and can be set by) the form
  3. The order of rows
  4. Which models are installed

How do you make a ModelForm update an existing object?

  1. form.update(obj)
  2. Pass instance=obj when creating the form
  3. Call obj.save(form)
  4. Use fields = "__all__"

Why call form.save(commit=False)?

  1. To validate without saving
  2. To get an unsaved instance so you can set extra fields before saving
  3. To delete the object
  4. To skip validation