TExcelTAD
Home › Django › Django Class-Based Views

Django Class-Based Views

So far our views have been functions. Django also lets you write views as classes. A class-based view (CBV) has one method per HTTP verb — get(), post(), put(), delete() — instead of an if request.method == ... ladder, and because it's a class you can reuse behaviour through inheritance and mixins.

Function-based view Class-based view
def books(request): ... class BooksView(View): def get(self, request): ...
branch on request.method one method per HTTP verb
reuse via decorators and helper functions reuse via inheritance, mixins and decorators
path("books/", books) path("books/", BooksView.as_view())

Neither style is "better" — many projects mix both. CBVs shine when several views share behaviour, and they power Django's generic views.

The View base class

Subclass django.views.View, add methods named after HTTP verbs, and hook the class into the URLconf with .as_view(), which turns it into a view function. Verbs you don't implement are answered with 405 Method Not Allowed automatically:

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"])
django.setup()
from django.http import HttpResponse
from django.views import View
from django.urls import path
from django.test import Client

class NotesView(View):
    notes = ["first note"]

    def get(self, request):
        return HttpResponse(" | ".join(self.notes))

    def post(self, request):
        self.notes.append(request.POST["text"])
        return HttpResponse("added", status=201)

urls.urlpatterns = [path("notes/", NotesView.as_view())]

c = Client()
print(c.get("/notes/").content.decode())
r = c.post("/notes/", {"text": "second note"})
print(r.status_code, r.content.decode())
print(c.get("/notes/").content.decode())
r = c.delete("/notes/")
print(r.status_code, "Allow:", r["Allow"])
first note
201 added
first note | second note
405 Allow: GET, POST, HEAD, OPTIONS

Django adds HEAD (answered by get()) and OPTIONS for you. Note that notes is a class attribute shared by every request — fine for a demo, but real data belongs in the database, because a new view instance is created for each request.

Configuration through class attributes

Class attributes act as settings. You can override them in subclasses, or pass them to as_view() in the URLconf — one class, several configurations:

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"])
django.setup()
from django.http import HttpResponse
from django.views import View
from django.urls import path
from django.test import Client

class GreetingView(View):
    greeting = "Hello"
    punctuation = "!"

    def get(self, request, name="world"):
        return HttpResponse(f"{self.greeting}, {name}{self.punctuation}")

class FrenchGreetingView(GreetingView):
    greeting = "Bonjour"

urls.urlpatterns = [
    path("hello/<str:name>/", GreetingView.as_view()),
    path("bonjour/<str:name>/", FrenchGreetingView.as_view()),
    path("xin-chao/", GreetingView.as_view(greeting="Xin chào", punctuation=" :)")),
]

c = Client()
for url in ["/hello/Duy/", "/bonjour/Duy/", "/xin-chao/"]:
    print(c.get(url).content.decode())
Hello, Duy!
Bonjour, Duy!
Xin chào, world :)

URL keyword arguments (like name) are passed to the method, and are also available as self.kwargs. The request is self.request.

Mixins: reusable behaviour

A mixin is a small class that adds one feature and is combined with a view through multiple inheritance. Put mixins before the base view in the class list. Django's own LoginRequiredMixin and PermissionRequiredMixin work this way; here's a home-made one:

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"])
django.setup()
from django.http import HttpResponse, JsonResponse, HttpResponseForbidden
from django.views import View
from django.urls import path
from django.test import Client

class ApiKeyRequiredMixin:
    """Reject requests without the right X-Api-Key header."""
    api_key = "letmein"

    def dispatch(self, request, *args, **kwargs):
        if request.headers.get("X-Api-Key") != self.api_key:
            return HttpResponseForbidden("missing or wrong API key")
        return super().dispatch(request, *args, **kwargs)

class JsonMixin:
    def render_json(self, data, status=200):
        return JsonResponse({"ok": status < 400, "data": data}, status=status)

class StatsView(ApiKeyRequiredMixin, JsonMixin, View):
    def get(self, request):
        return self.render_json({"users": 42, "posts": 7})

urls.urlpatterns = [path("stats/", StatsView.as_view())]

c = Client()
r = c.get("/stats/")
print(r.status_code, r.content.decode())
r = c.get("/stats/", headers={"X-Api-Key": "letmein"})
print(r.status_code, r.json())
print([cls.__name__ for cls in StatsView.__mro__])
403 missing or wrong API key
200 {'ok': True, 'data': {'users': 42, 'posts': 7}}
['StatsView', 'ApiKeyRequiredMixin', 'JsonMixin', 'View', 'object']

dispatch() is the method that every request goes through before reaching get()/post(); overriding it is how mixins add checks. The MRO (method resolution order) shows the order in which classes are searched — the mixin's dispatch() runs first and passes control on with super().

TemplateView and RedirectView

Django includes simple generic views for common jobs. TemplateView renders a template, with get_context_data() adding variables; RedirectView redirects:

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"],
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates",
                "OPTIONS": {"loaders": [("django.template.loaders.locmem.Loader", {
                    "about.html": "<h1>{{ title }}</h1><p>{{ members }} members, page {{ view.page_name }}</p>",
                })]}}],
)
django.setup()
from django.views.generic import TemplateView, RedirectView
from django.urls import path
from django.test import Client

class AboutView(TemplateView):
    template_name = "about.html"
    page_name = "about"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["title"] = "About the Bookshelf"
        context["members"] = 128
        return context

urls.urlpatterns = [
    path("about/", AboutView.as_view()),
    path("info/", RedirectView.as_view(url="/about/", permanent=True)),
]

c = Client()
print(c.get("/about/").content.decode())
r = c.get("/info/")
print(r.status_code, r["Location"])
<h1>About the Bookshelf</h1><p>128 members, page about</p>
301 /about/

Every class-based view puts itself in the context as view, so templates can read view attributes like {{ view.page_name }}.

Tip: To decorate a class-based view, either wrap it in the URLconf — login_required(MyView.as_view()) — or use @method_decorator(login_required, name="dispatch") on the class.

Test yourself

How do you connect a class-based view to a URL?

  1. path("x/", MyView)
  2. path("x/", MyView())
  3. path("x/", MyView.as_view())
  4. path("x/", MyView.get)

A View subclass only defines get(). What does a POST request receive?

  1. 200
  2. 404
  3. 405 Method Not Allowed
  4. 500

Where should a mixin appear in the list of base classes?

  1. After View
  2. Before the base view class
  3. It doesn't matter
  4. Mixins can't be combined with View