Skip to the workspace
Pebellslearn by building
Models, Views, Admin and Tests  ›  Lesson

Class-Based Views

Class-based views 16 minA class-based view organises a view as a class with one method per HTTP verb, and generic class-based views such as ListView and DetailView supply the common patterns so you only set what differs.

django / Class-Based Views

Explore each scene at your own pace.

01 · The rule

The rule

Class-Based Views

After a few weeks, the cookbook's views.py shows a pattern: list some objects, show one object, handle a form. Every list view looks the same apart from the model. Class-based views let Django own that repeated shape, so your code states only what is different.

The rule

A class per view, a method per verb; generic views fill in the rest.

The base View class sends each request to the method named after its HTTP verb:

from django.shortcuts import render
from django.views import View

class RecipeSearchView(View):
    def get(self, request):
        return render(request, "recipes/search.html")

    def post(self, request):
        ...   # handle the submitted search

If a verb has no method, say a DELETE, Django answers 405 Method Not Allowed for you. No if request.method == ... branches.

URL patterns need a function, so every class-based view is wired in with .as_view():

path("search/", views.RecipeSearchView.as_view(), name="search"),

The real payoff is generic views, ready-made classes for common jobs:

from django.views.generic import DetailView, ListView
from .models import Recipe

class RecipeListView(ListView):
    model = Recipe
    ordering = ["-created"]

class RecipeDetailView(DetailView):
    model = Recipe
path("", views.RecipeListView.as_view(), name="list"),
path("<slug:slug>/", views.RecipeDetailView.as_view(), name="detail"),

Those few lines replace both function views. From model = Recipe, Django works out the rest by convention:

  • ListView renders recipes/recipe_list.html with object_list (and recipe_list) in the context.
  • DetailView reads slug (or pk) from the URL, finds that recipe, raises 404 if none exists, and renders recipes/recipe_detail.html with object (and recipe).

To change behaviour, override an attribute or method: template_name, paginate_by = 10, or get_queryset() to filter.

Function views are not obsolete. A one-off page with unusual logic is often clearer as a function. Use classes when the job matches a pattern Django already knows.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.