🎓 A1Learner
🔍
0 of 50 lessons completed

Django ModelForms

A ModelForm is a form built from a model. It makes the form fields from the model fields.

The model

This model has one field for a title. The model class comes from an earlier lesson.

class Post(models.Model):
    title = models.CharField(max_length=100)

    class Meta:
        app_label = "blog"

The ModelForm

The Meta class names the model and the fields. The form gets a title field from the model.

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ["title"]

Save a valid form

The view builds the form from the posted values. A valid form saves a new post.

def save_post(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save()
            return HttpResponse("Saved: " + post.title)

Post a title

The post sends a title. The count shows one post now exists.

client = Client()
print(client.post("/save", {"title": "Hello"}).content.decode())
print(Post.objects.count())

Example

import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    SECRET_KEY="key",
    ROOT_URLCONF=__name__,
    ALLOWED_HOSTS=["*"],
    INSTALLED_APPS=[
        "django.contrib.contenttypes",
        "django.contrib.auth",
    ],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True}],
)
django.setup()

from django import forms
from django.db import connection, models
from django.http import HttpResponse
from django.urls import path
from django.test import Client


class Post(models.Model):
    title = models.CharField(max_length=100)

    class Meta:
        app_label = "blog"


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


class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ["title"]


def save_post(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save()
            return HttpResponse("Saved: " + post.title)
        return HttpResponse("Please type a title")
    return HttpResponse("Show the form")


urlpatterns = [path("save", save_post)]

client = Client()
print(client.post("/save", {"title": "Hello"}).content.decode())
print(Post.objects.count())
print(client.post("/save", {"title": ""}).content.decode())

Key points

  • A ModelForm builds its fields from a model.
  • The Meta class names the model and the fields.
  • form.save() makes the object and stores it.
  • A ModelForm checks the values before saving.
  • A ModelForm is a form built from a model.

In this example, the setup lines configure Django. The program creates the table directly. A real project uses migrations for this step. The PostForm class builds its fields from the Post model. The save_post view checks the request method. A POST with a title saves a new post. An empty title fails the check and gets a message. The test client posts Hello, prints the count of posts, then posts an empty title. The prints show the saved title, the count of 1, and the message.

Note

Only list fields the form should let a reader fill in.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does a ModelForm build its fields from?