Class-Based Views
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:
| ListView | DetailView | |
|---|---|---|
| Fetches | All objects (or your queryset) | One object, by pk or slug from the URL |
| Default template | events/event_list.html | events/event_detail.html |
| Context variables | object_list and event_list | object and event |
| If not found | Empty list | 404 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 method | Use it to |
|---|---|
template_name | Use a different template file |
context_object_name | Rename the variable in the template |
queryset | Show a filtered or ordered set of objects |
paginate_by | Split 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"]).
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.
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.
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 views | Class-based views |
|---|---|
| Explicit: you can read every step | Concise: behaviour is inherited |
| Great for unusual or one-off logic | Great for standard list, detail and form pages |
| Easy for beginners to debug | Need 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()inurls.py. ListViewandDetailViewuse templates namedapp/model_list.htmlandapp/model_detail.htmlby default.- Customise with attributes like
paginate_byor methods likeget_queryset(). - Always call
super()when overridingget_context_data().
Tip: use the ← and → keys to move between pages.
