← Back to Django, page 2

django-0022 · Medium mid

How do class-based views work in Django, and how do you customise generic views like ListView and DetailView?

A class-based view is a class whose as_view() returns a function; dispatch() sends each request to a method named after the HTTP verb, such as get() or post(). Generic views like ListView, DetailView, CreateView and UpdateView implement common patterns, and you customise them by setting attributes (model, template_name, paginate_by) or overriding hooks such as get_queryset(), get_context_data() and form_valid().

Full answer

View.as_view() builds a function Django can call. For each request it creates a new instance of the class, stores request, args and kwargs on it, and calls dispatch(), which calls get(), post() and so on. A method that is not defined returns 405 Method Not Allowed.

Generic views are pre-built patterns:

  • ListView: a page of objects (object_list, pagination with paginate_by).
  • DetailView: one object looked up by pk or slug from the URL, 404 if missing.
  • CreateView / UpdateView / DeleteView: forms with redirect on success.
  • TemplateView, RedirectView, FormView.

They are built from mixins (MultipleObjectMixin, SingleObjectMixin, FormMixin), so the same hooks appear everywhere:

  • get_queryset(): which rows are visible. Put user scoping and select_related here.
  • get_object(): the single object for detail views.
  • get_context_data(**kwargs): add template variables; always call super() first.
  • form_valid(form): set fields like the owner before saving.
  • get_success_url().

Access control comes from mixins placed to the left of the view class: class MyLoans(LoginRequiredMixin, ListView). Python's method resolution order (MRO) runs left to right, so the mixin's dispatch() runs first.

When to choose them: CBVs reduce repetition for CRUD screens. A function view is often clearer for one-off logic with several branches. Many teams use both.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.db import models, connection
from django.http import HttpResponse
from django.test import RequestFactory
from django.views import View
from django.views.generic import ListView


class Book(models.Model):
    title = models.CharField(max_length=60)
    owner = models.CharField(max_length=30)
    class Meta:
        app_label = "school"
        ordering = ["title"]


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

for t, o in [("Godan", "nisha"), ("Gitanjali", "nisha"), ("Nirmala", "tom")]:
    Book.objects.create(title=t, owner=o)


class MyBooks(ListView):
    model = Book
    paginate_by = 10

    def get_queryset(self):
        return super().get_queryset().filter(owner=self.kwargs["owner"])

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx["total"] = self.object_list.count()
        return ctx

    def render_to_response(self, context, **kwargs):
        titles = [b.title for b in context["object_list"]]
        return HttpResponse(f"{titles} total={context['total']}")


class Ping(View):
    def get(self, request):
        return HttpResponse("pong")


rf = RequestFactory()
print(MyBooks.as_view()(rf.get("/"), owner="nisha").content.decode())
print(Ping.as_view()(rf.get("/")).content.decode(), Ping.as_view()(rf.post("/")).status_code)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. render_to_response is overridden here only to avoid needing a template file. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['Gitanjali', 'Godan'] total=2 pong 405

Key points

  • as_view() creates a new instance per request and calls dispatch()
  • dispatch() routes to get(), post() and so on
  • Override get_queryset, get_context_data, form_valid
  • Mixins go to the left because of MRO
  • Missing method handlers return 405

Common mistakes

  • Storing request data on the class instead of the instance (class attributes are shared)
  • Overriding get_context_data without calling super()
  • Placing LoginRequiredMixin to the right of the view class
  • Filtering by user in the template instead of get_queryset()

Follow-ups

  • Explain the MRO for class MyView(LoginRequiredMixin, UpdateView)
  • How would you set the logged-in user as owner in CreateView?
  • When would you prefer a function view?

Tips

  • Describe the as_view -> dispatch -> get flow
  • Name three hooks and what each controls
  • Mention mixin ordering and why it matters