Django · Chapter 8 of 8
Django CRUD with ModelForm and generic class-based views
14 min study · Examples checked with Django 6.1 on Python 3.14 ·
The suggestion form in chapter 7 duplicated information the model already has: field types, lengths, choices. For forms that create or edit a model, Django generates the form from the model with ModelForm, and it provides generic class-based views for the usual pages: a list, a detail page, a create form, an edit form and a delete action. This last chapter of the track builds a small staff area for managing lessons with them, restricted to users who have the right permissions.
A ModelForm
Add to catalog/forms.py:
class LessonForm(forms.ModelForm):
class Meta:
model = Lesson
fields = ["title", "course", "minutes", "level", "summary", "tags", "published"]
widgets = {"summary": forms.Textarea(attrs={"rows": 4})}
Each model field becomes a form field of the matching type, with its validators, choices, max_length and blank setting: course becomes a drop-down of courses and tags a multiple choice. Calling is_valid() also runs the model’s own validation, including unique checks, and form.save() creates or updates the object, many-to-many links included. Always list fields explicitly. With fields = "__all__", a field added to the model later, such as an internal featured flag, would silently become editable by anyone who can submit the form.
Generic views for every page
Create catalog/editing.py:
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse_lazy
from django.views.generic import CreateView, DeleteView, DetailView, ListView, UpdateView
from .forms import LessonForm
from .models import Lesson
class LessonListView(ListView):
queryset = Lesson.objects.select_related("course").order_by("title")
paginate_by = 20
class LessonDetailView(DetailView):
model = Lesson
class LessonCreateView(PermissionRequiredMixin, SuccessMessageMixin, CreateView):
model = Lesson
form_class = LessonForm
permission_required = "catalog.add_lesson"
success_message = "Lesson “%(title)s” was created."
class LessonUpdateView(PermissionRequiredMixin, SuccessMessageMixin, UpdateView):
model = Lesson
form_class = LessonForm
permission_required = "catalog.change_lesson"
success_message = "Lesson “%(title)s” was saved."
class LessonDeleteView(PermissionRequiredMixin, DeleteView):
model = Lesson
permission_required = "catalog.delete_lesson"
http_method_names = ["post"]
success_url = reverse_lazy("catalog:manage")
Each class does one job, and the attributes configure it. ListView fetches the queryset and paginates it, 20 per page. DetailView looks up the object by the pk from the URL and returns 404 when it doesn’t exist. CreateView and UpdateView implement the GET/POST form pattern from chapter 7: show the form, validate, save, redirect. After saving, they redirect to get_absolute_url() of the object, so Lesson.get_absolute_url should now return reverse("catalog:lesson-detail", args=[self.pk]). DeleteView deletes on POST and redirects to success_url; reverse_lazy is needed there because the URL configuration isn’t loaded yet when the class is defined.
Mixins add behaviour. PermissionRequiredMixin sends anonymous users to the login page and answers 403 to logged-in users without the permission. Django creates add, change, delete and view permissions for every model, assigned to users or groups in the admin. SuccessMessageMixin adds a message after a successful save, filled with the form’s values. http_method_names = ["post"] makes deletion POST-only: a GET request gets 405, so a link or a crawler can never delete anything.
URLs and templates
In catalog/urls.py, import editing next to views and add:
path("manage/", editing.LessonListView.as_view(), name="manage"),
path("manage/new/", editing.LessonCreateView.as_view(), name="lesson-create"),
path("manage/<int:pk>/", editing.LessonDetailView.as_view(), name="lesson-detail"),
path("manage/<int:pk>/edit/", editing.LessonUpdateView.as_view(), name="lesson-update"),
path("manage/<int:pk>/delete/", editing.LessonDeleteView.as_view(), name="lesson-delete"),
Generic views find their templates by convention: catalog/lesson_list.html for the list, catalog/lesson_detail.html for the detail page, and catalog/lesson_form.html for both create and update. The list template loops over lesson_list and uses page_obj.has_next and page_obj.next_page_number for paging links; the perms variable lets it show a “New lesson” link only to users who may add lessons. The form template is short:
{% extends "catalog/base.html" %}
{% block content %}
<h1>{% if object %}Edit {{ object.title }}{% else %}New lesson{% endif %}</h1>
<form method="post">
{% csrf_token %}
{{ form.as_div }}
<button type="submit">Save</button>
</form>
{% endblock %}
object is set when editing and missing when creating, so one template serves both. The detail page shows the lesson and holds the delete button, which is a form, because deleting must be a POST with a CSRF token:
{% extends "catalog/base.html" %}
{% block content %}
{% for message in messages %}<p class="notice">{{ message }}</p>{% endfor %}
<h1>{{ lesson.title }}</h1>
<p>{{ lesson.minutes }} min · {{ lesson.get_level_display }} · {{ lesson.published|yesno:"published,draft" }}</p>
<p>{{ lesson.summary|linebreaksbr }}</p>
<a href="{% url 'catalog:lesson-update' lesson.pk %}">Edit</a>
<form method="post" action="{% url 'catalog:lesson-delete' lesson.pk %}">
{% csrf_token %}<button type="submit">Delete</button>
</form>
{% endblock %}
Follow the paths
These results came from Django’s test client, as an anonymous visitor, an editor with all three permissions, and a reader without them:
anonymous GET /manage/new/ 302 -> /accounts/login/?next=/manage/new/
editor POST /manage/new/ (valid) 302 -> /manage/1/ "Lesson “Loops” was created."
editor POST /manage/new/ (duplicate title, 0 minutes)
200 with "Lesson with this Title already exists." and
"Ensure this value is greater than or equal to 1."
editor GET /manage/1/delete/ 405
editor POST /manage/1/delete/ 302 -> /manage/
editor GET /manage/9/edit/ 404
reader GET /manage/new/ 403
Note the anonymous redirect to /accounts/login/: adding Django’s login views with path("accounts/", include("django.contrib.auth.urls")) and a registration/login.html template completes it. One more result is worth knowing. When the editor submitted the edit form for “Loops” without the published field, the lesson became unpublished. An unticked checkbox sends nothing, and a model form treats a missing boolean as False. Browsers always send the form’s other fields, so this only bites clients that post partial data; for partial updates, build a form with only the fields being changed.
Before going live
Run the project’s tests and python manage.py check --deploy, set DEBUG, SECRET_KEY and ALLOWED_HOSTS from the environment (chapter 1), switch to PostgreSQL for concurrent writes, run migrate and collectstatic as part of each deployment, and serve the app with a production server such as Gunicorn or Uvicorn behind a web server. Django’s deployment checklist in its documentation covers the rest.
Practice
Restrict the list to the current user’s lessons by adding an owner foreign key to Lesson (set automatically on create, never shown in the form), and make the update and delete views return 404 for lessons owned by someone else.
Answer check: in LessonCreateView, override form_valid(self, form) to set form.instance.owner = self.request.user before calling super().form_valid(form), and leave owner out of fields. In the list, update and delete views, override get_queryset() to return Lesson.objects.filter(owner=self.request.user), so other users’ lessons are simply not found (404) instead of forbidden, which also hides that they exist.
Summary
ModelForm builds a form from a model, with an explicit fields list. ListView, DetailView, CreateView, UpdateView and DeleteView implement the standard pages, finding templates by naming convention and redirecting with get_absolute_url or success_url. Protect them with PermissionRequiredMixin, confirm actions with SuccessMessageMixin, and only ever delete on POST.