Skip to content
Kuza Ndoto Academy

Class-Based Views

IntermediateChapter 2 · Page 8 of 234 min readUpdated 15 Nov 2026

Class-based views (CBVs) let you write common pages, such as a list of items or a single item's details, by configuring a ready-made class instead of writing the whole function yourself. They save a lot of repeated code once your site has many similar pages.

From function to class

This page uses the Event model you'll build on the Models page. Here's a function-based list view and its class-based equivalent:

events/views.py (function-based)

from django.shortcuts import render

from .models import Event


def event_list(request):
    events = Event.objects.all()
    return render(request, "events/event_list.html", {"event_list": events})

events/views.py (class-based)

from django.views.generic import ListView

from .models import Event


class EventListView(ListView):
    model = Event

Those two lines do the same job. ListView already knows how to fetch every object, choose a template and render it. You only tell it which model to use.

In urls.py, call .as_view() to turn the class into a function Django can call:

events/urls.py

from django.urls import path

from . import views

app_name = "events"

urlpatterns = [
    path("", views.EventListView.as_view(), name="event_list"),
    path("<int:pk>/", views.EventDetailView.as_view(), name="event_detail"),
]

ListView and DetailView

These two generic views cover most read-only pages. They follow naming conventions so you don't have to configure much:

ListViewDetailView
FetchesAll objects (or your queryset)One object, by pk or slug from the URL
Default templateevents/event_list.htmlevents/event_detail.html
Context variablesobject_list and event_listobject and event
If not foundEmpty list404 response

The template name pattern is <app>/<model>_list.html and <app>/<model>_detail.html, all lowercase.

events/views.py

from django.views.generic import DetailView, ListView

from .models import Event


class EventListView(ListView):
    model = Event
    context_object_name = "events"   # use {{ events }} instead of {{ event_list }}
    paginate_by = 10                  # 10 events per page


class EventDetailView(DetailView):
    model = Event

events/templates/events/event_detail.html

<h1>{{ event.title }}</h1>
<p>{{ event.venue }}, {{ event.starts_at|date:"D j M Y, H:i" }}</p>
<p>{{ event.description }}</p>

Customising a generic view

You customise CBVs in two ways: by setting attributes and by overriding methods.

Attribute or methodUse it to
template_nameUse a different template file
context_object_nameRename the variable in the template
querysetShow a filtered or ordered set of objects
paginate_bySplit long lists into pages
get_queryset()Build the queryset using the request, e.g. a search term
get_context_data()Add extra variables to the template

Here's a list view that only shows upcoming events, supports a search box and adds a page heading:

events/views.py

from django.utils import timezone
from django.views.generic import ListView

from .models import Event


class UpcomingEventListView(ListView):
    template_name = "events/event_list.html"
    context_object_name = "events"
    paginate_by = 10

    def get_queryset(self):
        events = Event.objects.filter(starts_at__gte=timezone.now())
        query = self.request.GET.get("q")
        if query:
            events = events.filter(title__icontains=query)
        return events

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["heading"] = "Upcoming events"
        context["query"] = self.request.GET.get("q", "")
        return context

Inside a CBV, the request is available as self.request, and URL values as self.kwargs (for example self.kwargs["pk"]).

Common mistake

Forgetting super().get_context_data(**kwargs) when overriding get_context_data(). If you build a new dictionary from scratch, you lose events, page_obj and everything else the parent class added, and the template shows nothing.

Common mistake

Writing views.EventListView in urls.py without .as_view(). Django can't use a class directly as a view and raises an error when the URLconf loads or the page is requested.

Other generic views

  • TemplateView: renders a template with no database work, e.g. an About page: path("about/", TemplateView.as_view(template_name="about.html")).
  • RedirectView: redirects to another URL.
  • CreateView, UpdateView, DeleteView: forms for creating, editing and deleting objects. These are covered on the Model Forms page.
View TemplateView ListView DetailView CreateView UpdateView DeleteView EventListView EventCreateView You write:
Figure 1. A simplified view of Django's generic views (the mixins in between are left out). Your class inherits all of its parent's behaviour and changes only what you override.

Mixins add extra behaviour to any CBV. For example, LoginRequiredMixin restricts a view to logged-in users; you'll use it on the User Authentication page.

Functions or classes?

Function-based viewsClass-based views
Explicit: you can read every stepConcise: behaviour is inherited
Great for unusual or one-off logicGreat for standard list, detail and form pages
Easy for beginners to debugNeed to know which methods to override

Both are fully supported. Many professional projects mix them: CBVs for standard pages and functions for anything unusual. Use whichever makes a particular view easiest to read.

Key points

  • CBVs are classes you configure; call .as_view() in urls.py.
  • ListView and DetailView use templates named app/model_list.html and app/model_detail.html by default.
  • Customise with attributes like paginate_by or methods like get_queryset().
  • Always call super() when overriding get_context_data().
Up next · New chapter: TemplatesDjango TemplatesGenerate HTML with data.
→

Tip: use the ← and → keys to move between pages.