Chapter 10 · 10 min read
Forms with ModelForm
Forms with ModelForm
Websites collect input: sign-ups, comments, posts. Handling input safely means validating it, protecting against forged requests, and showing helpful errors. Django's form system does all of that. A ModelForm builds a form directly from a model so you write almost nothing twice.
What you will learn
- How a form class turns a model into HTML inputs and validation.
- The GET and POST pattern used by form views.
- Why
{% csrf_token %}is required. - How to add custom validation with
clean_<field>(). - Why you redirect after a successful POST.
The two faces of a form view
A form view handles the same URL in two situations:
| Request | What the view does |
|---|---|
GET (the visitor opens the page) | Create an empty form and show it |
POST (the visitor submits) | Fill the form with the submitted data, validate it, save it and redirect, or show the form again with errors |
Step by step
In the next two chapters you will build the login system. For now, log in at /admin/ first: the admin login creates a session that works for the whole site, so request.user will be you.
1. The form class
Create blog/forms.py:
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "body", "published"]
def clean_title(self):
title = self.cleaned_data["title"]
if len(title) < 5:
raise forms.ValidationError("Title must be at least 5 characters.")
return title
class Metalinks the form to the model and lists the fields to include. Always list fields explicitly. The author is deliberately left out: users must not choose it.clean_title()runs after Django's built-in checks for thetitlefield. RaiseValidationErrorto reject a value, or return the cleaned value.self.cleaned_dataholds validated values as proper Python types.
2. The view
Replace blog/views.py:
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from .forms import PostForm
from .models import Post
def post_list(request):
posts = Post.objects.filter(published=True).select_related("author")
return render(request, "blog/post_list.html", {"post_list": posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, "blog/post_detail.html", {"post": post})
@login_required
def post_create(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect(post)
else:
form = PostForm()
return render(request, "blog/post_form.html", {"form": form})
Walkthrough of post_create:
@login_requiredsends anonymous visitors to the login page.- On POST,
PostForm(request.POST)binds the submitted data.is_valid()runs all validation. form.save(commit=False)builds aPostin memory without saving, so you can fill inauthor. Thenpost.save()writes it.redirect(post)usespost.get_absolute_url()and sends the browser to the new post. Redirecting after a successful POST means that pressing refresh does not submit the form twice. This is the Post/Redirect/Get pattern.- If the form is invalid, the view falls through and renders the same form again; the form object now carries error messages.
- On GET, an empty
PostForm()is shown.
3. The URL
In blog/urls.py add one line to urlpatterns:
path("post/new/", views.post_create, name="create"),
The complete file becomes:
from django.urls import path
from . import views
app_name = "blog"
urlpatterns = [
path("", views.post_list, name="home"),
path("post/new/", views.post_create, name="create"),
path("post/<int:pk>/", views.post_detail, name="detail"),
]
4. The template
Create blog/templates/blog/post_form.html:
{% extends "blog/base.html" %}
{% block title %}Write a post{% endblock %}
{% block content %}
<h1>Write a post</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
{% endblock %}
method="post"is required for forms that change data.{% csrf_token %}inserts a hidden secret. Django's CSRF protection rejects POST requests that do not carry it, which stops other websites from submitting forms on behalf of your logged-in users.{{ form.as_p }}renders each field wrapped in a paragraph, with labels and error messages.
Finally, add a link to the writing page on the list page, just under the heading:
<p><a href="{% url 'blog:create' %}">Write a post</a></p>
What the model gives the form for free
| Model field | Form input |
|---|---|
CharField(max_length=200) | Text input with maximum length |
TextField | Textarea |
BooleanField | Checkbox |
DateTimeField | Date/time input |
ForeignKey | Drop-down of related objects |
Validation rules such as required, maximum length and uniqueness also come from the model.
Check it works
- Log in at
/admin/, then open http://127.0.0.1:8000/post/new/. - Submit a title shorter than 5 characters: an error appears next to the field and nothing is saved.
- Submit a valid post: you land on its detail page.
- Refresh that page: no duplicate post is created.
Exercises with solutions
Exercise 1: reject shouting
Reject titles that are entirely in capital letters.
Solution. Extend clean_title:
def clean_title(self):
title = self.cleaned_data["title"]
if len(title) < 5:
raise forms.ValidationError("Title must be at least 5 characters.")
if title.isupper():
raise forms.ValidationError("Please do not write the title in capitals.")
return title
Exercise 2: hide a field
Make every new post published, and remove the checkbox.
Solution. Remove "published" from fields. Because the model's default is True, new posts are published. If you wanted to be explicit you could set post.published = True in the view before saving.
Exercise 3: friendlier labels and help
Give the body field a label and a help text.
Solution.
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "body", "published"]
labels = {"body": "Your story"}
help_texts = {"body": "Write at least a few sentences."}
Common mistakes
- Forgetting
{% csrf_token %}. The page answers403 CSRF verification failed. - Forgetting
method="post"on the form. The data travels in the URL instead. - Skipping the redirect after a successful POST. Refreshing re-submits the form.
- Not setting the author. Saving fails with
NOT NULL constraint failed: blog_post.author_id. - Forgetting the
fieldslist inMeta. Django refuses to build the form. - Including sensitive fields like the author in the form. Users could then choose them.
Key takeaways
- A
ModelFormbuilds inputs and validation from a model. - Form views follow GET to show, POST to process, redirect on success.
commit=Falselets you fill fields the user must not choose.- Always include
{% csrf_token %}in POST forms.
Official links
- Working with forms: https://docs.djangoproject.com/en/6.1/topics/forms/
- ModelForms: https://docs.djangoproject.com/en/6.1/topics/forms/modelforms/
- Tutorial part 4: https://docs.djangoproject.com/en/6.1/intro/tutorial04/
