Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 77 ยท URLs and Views

Class-Based Views

Learn how Django class-based views work. Write View subclasses, understand as_view() and dispatch(), use TemplateView and RedirectView, add mixins and choose between CBVs and FBVs.

A function-based view is a function from request to response. A class-based view (CBV) is a class that produces such a function. Why bother? Because classes give you inheritance: the common work (choosing a handler by HTTP method, rendering a template, redirecting) lives in a base class, and your view overrides only the parts that differ.

In this lesson you will write a view from the base View class, see what as_view() and dispatch() actually do, use the ready-made TemplateView and RedirectView, and compose behavior with mixins. You should be comfortable with Function-Based Views and with Python classes and inheritance.

The View base class

Subclass django.views.View and define one method per HTTP verb you want to support, named in lowercase: get, post, put, patch, delete. Each receives the request (plus any URL arguments) and returns a response.

Python A View with get() and post()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the output closely, because it shows the machinery:

  • A request for a verb you did not define (DELETE) gets 405 Method Not Allowed, and the Allow header lists what is supported. You wrote no code for that.
  • OPTIONS works automatically, and HEAD falls back to your get().
  • as_view() returned a plain function. The URL resolver only knows how to call functions, so the class must be turned into one.

as_view() and dispatch()

as_view() is a class method. When you call it, it returns a function that does this on every request:

  1. Create a new instance of your class (so instance attributes are never shared between requests).
  2. Store request, args and kwargs on it.
  3. Call dispatch().

dispatch() looks at request.method, finds the method with that lowercase name, and calls it. If there is none, it calls http_method_not_allowed().

flowchart TD
    A["URLconf: path('x/', MyView.as_view())"] --> B["view function called with request"]
    B --> C["new MyView instance created"]
    C --> D["dispatch()"]
    D -->|"method = GET"| E["get()"]
    D -->|"method = POST"| F["post()"]
    D -->|"no matching method"| G["405 Method Not Allowed"]

as_view() builds a fresh instance for each request; dispatch() routes to the method named after the HTTP verb.

Keyword arguments passed to as_view() override class attributes of the same name, as greeting="Good evening" did above. The attribute must already exist on the class, otherwise Django raises a TypeError. This is a handy way to reuse one class with different settings in several URL patterns.

Never keep per-request state in a class attribute such as items = []. A class attribute is shared by every request and every thread. Store request-specific data on self inside a method.

Ready-made views: TemplateView and RedirectView

Many views do nothing but show a template or redirect. Django ships classes for both so you write almost no code.

TemplateView renders template_name with a context. Override get_context_data() to add variables, always calling super() first so the base class can contribute its values. RedirectView issues a redirect to a url or to a named URL pattern with pattern_name.

Python TemplateView, RedirectView and a mixin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice three things. extra_context on TemplateView.as_view() is the quickest way to add static variables without subclassing. permanent=True turns the redirect into a 301 (cached by browsers and search engines) instead of the default 302. And ROOT_URLCONF=__name__ simply tells Django that the URL patterns are in this very file; in a real project it points at myproject.urls (see URL Routing).

Mixins

The last class in the example, JsonOnlyMixin, is a mixin: a small class that adds one behavior and is meant to be combined with others. It overrides dispatch(), checks something, and otherwise calls super().dispatch(...) so the next class in the chain continues the work. The printed MRO (method resolution order) shows the order Python walks: StatusView, then JsonOnlyMixin, then View.

Two conventions keep mixins working:

  • List mixins before the base view class. Python searches left to right, so class StatusView(JsonOnlyMixin, View) runs the mixin's dispatch() first. Reverse the bases and the mixin is never reached.
  • Always call super() in overridden methods, unless you intend to stop the chain.

Django's own authentication helpers are mixins too, for example LoginRequiredMixin, which you will meet in Users and Authentication.

Choosing CBV or FBV

Neither style is better in general. Use this as a guide:

Situation Prefer
Standard list, detail, create, edit or delete pages CBV (the generic views do most of the work)
Same behavior needed in many views (auth, caching headers) CBV with mixins, or a decorator on an FBV
One-off logic, a webhook, a tiny endpoint FBV
Logic that reads best as one top-to-bottom story FBV
A view with several HTTP methods sharing helpers CBV

A function stays easier to read when the code is short and unique. A class pays off when you reuse and customize. Many projects mix both, and that is fine.

To apply a function decorator to a CBV, wrap the result of as_view() in the URLconf (login_required(MyView.as_view())) or use method_decorator on the class. Both are plain Python; there is no special CBV decorator system.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does MyView.as_view() return?

    URL patterns need a callable view function. as_view() builds one that creates a new instance per request and routes it through dispatch().
  2. 2. A View defines only get(). What does a DELETE request receive?

    dispatch() finds no delete() method and calls http_method_not_allowed(), which answers 405 and lists the allowed verbs.
  3. 3. Which class definition makes the mixin's dispatch() run first?

    Python resolves methods left to right along the MRO, so the mixin must come before View.
  4. 4. Why should you avoid a mutable class attribute such as items = [] for per-request data?

    Only the instance is created per request. Class attributes are shared, so request data belongs on self.

Summary

  • A class-based view is a class with methods named after HTTP verbs; as_view() turns it into the function the URLconf needs.
  • A new instance is created for every request, and dispatch() picks the handler or answers 405.
  • Keyword arguments to as_view() override existing class attributes, so one class can serve several URLs.
  • TemplateView and RedirectView cover the simplest pages with almost no code; extend get_context_data() and call super().
  • Mixins add reusable behavior; put them before the base view and call super().
  • Choose CBVs for reuse and standard pages, FBVs for short one-off logic.

Next, let Django build whole pages from a model in Generic Display and Editing Views.