TExcelTAD
Home › Django › Django Generic Views

Django Generic Views

Look at enough Django projects and you'll see the same views again and again: list some objects, show one object, a form to create one, a form to edit one, a confirmation to delete one. Django packages these patterns as generic class-based views. You tell them the model and template, and they do the querying, 404 handling, form processing and redirecting.

View Does Default template Context variables
ListView list a QuerySet, optional pagination <app>/<model>_list.html object_list, <model>_list, page_obj
DetailView show one object by pk or slug (404 if missing) <app>/<model>_detail.html object, <model>
CreateView form to create an object <app>/<model>_form.html form
UpdateView form to edit an object <app>/<model>_form.html form, object
DeleteView confirm and delete <app>/<model>_confirm_delete.html object

ListView and DetailView

A complete list + detail pair takes only a few lines. The playground's locmem loader holds the two templates under their default names:

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:"}},
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates",
                "OPTIONS": {"loaders": [("django.template.loaders.locmem.Loader", {
                    "demo/book_list.html": "{% for book in book_list %}{{ book.pk }}. {{ book.title }}\n{% endfor %}",
                    "demo/book_detail.html": "{{ book.title }} ({{ book.year }}) - also as object: {{ object.title }}",
                })]}}],
)
django.setup()
from django.db import models, connection
from django.views.generic import ListView, DetailView
from django.urls import path
from django.test import Client

class Book(models.Model):
    title = models.CharField(max_length=100)
    year = models.IntegerField()
    class Meta:
        app_label = "demo"
        ordering = ["title"]

with connection.schema_editor() as editor:
    editor.create_model(Book)
for title, year in [("Persepolis", 2000), ("Maus", 1991), ("Watchmen", 1987)]:
    Book.objects.create(title=title, year=year)

class BookListView(ListView):
    model = Book

class BookDetailView(DetailView):
    model = Book

urls.urlpatterns = [
    path("books/", BookListView.as_view()),
    path("books/<int:pk>/", BookDetailView.as_view()),
]

c = Client()
print(c.get("/books/").content.decode())
print(c.get("/books/2/").content.decode())
print(c.get("/books/99/").status_code)
2. Maus
1. Persepolis
3. Watchmen

Maus (1991) - also as object: Maus
404

ListView used the model's Meta.ordering. DetailView looked up pk from the URL and returned 404 when it didn't exist — no get_object_or_404 needed.

Customising: queryset, context and pagination

Override attributes for simple changes and methods for dynamic ones. get_queryset() can read self.request and self.kwargs; paginate_by splits the list into pages selected with ?page=N:

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:"}},
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates",
                "OPTIONS": {"loaders": [("django.template.loaders.locmem.Loader", {
                    "catalog.html": (
                        "{{ heading }} - page {{ page_obj.number }} of {{ paginator.num_pages }}: "
                        "{% for p in products %}{{ p.name }}{% if not forloop.last %}, {% endif %}{% endfor %}"
                        "{% if page_obj.has_next %} [next: ?page={{ page_obj.next_page_number }}]{% endif %}"),
                })]}}],
)
django.setup()
from django.db import models, connection
from django.views.generic import ListView
from django.urls import path
from django.test import Client

class Product(models.Model):
    name = models.CharField(max_length=30)
    category = models.CharField(max_length=20)
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Product)
for i, cat in enumerate(["tea", "tea", "coffee", "tea", "tea", "coffee", "tea"], start=1):
    Product.objects.create(name=f"{cat.title()} #{i}", category=cat)

class CategoryView(ListView):
    template_name = "catalog.html"
    context_object_name = "products"
    paginate_by = 2

    def get_queryset(self):
        return Product.objects.filter(category=self.kwargs["cat"]).order_by("id")

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["heading"] = self.kwargs["cat"].upper()
        return context

urls.urlpatterns = [path("shop/<slug:cat>/", CategoryView.as_view())]

c = Client()
print(c.get("/shop/tea/").content.decode())
print(c.get("/shop/tea/?page=3").content.decode())
print(c.get("/shop/coffee/").content.decode())
print(c.get("/shop/tea/?page=9").status_code)
TEA - page 1 of 3: Tea #1, Tea #2 [next: ?page=2]
TEA - page 3 of 3: Tea #7
COFFEE - page 1 of 1: Coffee #3, Coffee #6
404
Attribute / method Purpose
model / queryset / get_queryset() which objects
template_name template instead of the default name
context_object_name name of the list/object in the template
paginate_by page size; adds page_obj, paginator, is_paginated
get_context_data() add extra template variables
slug_field, slug_url_kwarg look up DetailView objects by slug instead of pk

CreateView, UpdateView, DeleteView

The editing views combine a ModelForm with the standard GET/POST cycle. On success they redirect to success_url (or the object's get_absolute_url()):

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:"}},
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates",
                "OPTIONS": {"loaders": [("django.template.loaders.locmem.Loader", {
                    "demo/task_form.html": "{% if object %}Edit #{{ object.pk }}{% else %}New task{% endif %} {{ form.errors.title.0 }}",
                    "demo/task_confirm_delete.html": "Delete {{ object.title }}?",
                })]}}],
)
django.setup()
from django.db import models, connection
from django.views.generic import CreateView, UpdateView, DeleteView
from django.urls import path, reverse_lazy
from django.test import Client

class Task(models.Model):
    title = models.CharField(max_length=50)
    done = models.BooleanField(default=False)
    class Meta:
        app_label = "demo"

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

class TaskCreate(CreateView):
    model = Task
    fields = ["title"]
    success_url = reverse_lazy("tasks")

class TaskUpdate(UpdateView):
    model = Task
    fields = ["title", "done"]
    success_url = reverse_lazy("tasks")

class TaskDelete(DeleteView):
    model = Task
    success_url = reverse_lazy("tasks")

urls.urlpatterns = [
    path("tasks/", lambda r: None, name="tasks"),
    path("tasks/new/", TaskCreate.as_view()),
    path("tasks/<int:pk>/edit/", TaskUpdate.as_view()),
    path("tasks/<int:pk>/delete/", TaskDelete.as_view()),
]

def tasks():
    return list(Task.objects.order_by("id").values_list("title", "done"))

c = Client()
print(c.get("/tasks/new/").content.decode())
print(c.post("/tasks/new/", {"title": ""}).content.decode())
r = c.post("/tasks/new/", {"title": "Plan trip"})
print(r.status_code, r["Location"], tasks())
r = c.post("/tasks/1/edit/", {"title": "Plan trip to Sapa", "done": "on"})
print(r.status_code, tasks())
print(c.get("/tasks/1/delete/").content.decode())
r = c.post("/tasks/1/delete/")
print(r.status_code, tasks())
New task 
New task This field is required.
302 /tasks/ [('Plan trip', False)]
302 [('Plan trip to Sapa', True)]
Delete Plan trip to Sapa?
302 []

reverse_lazy() is needed for class attributes, because the URLconf isn't loaded yet when the class body runs.

Tip: When a generic view does 90% of what you need, override one or two methods (get_queryset, form_valid, get_success_url). When you find yourself overriding everything, a plain function view is probably clearer.

Test yourself

Which generic view shows a single object and returns 404 if it doesn't exist?

  1. ListView
  2. DetailView
  3. TemplateView
  4. RedirectView

What is the default template name for ListView with model Book in app shop?

  1. shop/book.html
  2. shop/book_list.html
  3. book_list.html
  4. shop/list.html

Why use reverse_lazy() for success_url on a class?

  1. It's faster
  2. URLs can't be reversed while the class body is being defined at import time
  3. It adds a query string
  4. It's required for all URLs