Class-Based Views (CBV) Refactoring
In this chapter you will learn Django's class-based views (CBV), and refactor the home page and detail page with more concise code.
FBV vs CBV
So far, all our views have been written with functions (Function-Based View, FBV).
Django also provides Class-Based Views (CBV), which use classes to encapsulate view logic.
| Feature | FBV (function view) | CBV (class view) |
|---|---|---|
| Amount of code | Flexible, but common logic needs to be written repeatedly | Only a few lines of code needed after inheriting generic views |
| Readability | Linear flow, clear logic | Inheritance chain needs tracing, but clear once familiar |
| Reusability | Encapsulated through functions | Composed through Mixins (a feature of Django) |
| Applicable scenarios | Pages with simple logic and clear flow | Patterned pages such as create, read, update, delete |
| HTTP method dispatch | Manual if request.method == 'POST' | Automatically dispatch to get() / post() methods |
Neither is absolutely better; Django projects usually mix FBV and CBV: use FBV for complex logic and CBV for standard CRUD.
ListView — list page refactoring
The home page's index view essentially: query the post list → render the template.
This kind of patterned logic, Django's ListView has already been written for you.
Example
File path: blog/views.py
from
django.
views
.
generic
import
ListView
from
django.
db
.
models
import
Q
from
.
models
import
Post
,
Category
class
PostListView
(
ListView
)
:
"""Blog home page: inherit ListView, display the post list"""
model
=
Post
Specify model
template_name
=
'blog/index.html'
Specify the template (default: blog/post_list.html)
context_object_name
=
'posts'
The variable name used in the template (default: object_list)
paginate_by
=
12
12 items per page (pagination)
ordering
=
[
'-created_at'
]
Sorting
def
get_queryset
(
self
)
:
"""Override the query method: support category filtering + keyword search"""
queryset
=
super
(
)
.
get_queryset
(
)
Category filtering
self
.
category_slug
=
self
.
request
.
GET
.
get
(
'category'
,
''
)
if
self
.
category_slug
:
queryset
=
queryset.
filter
(
category__slug
=
self
.
category_slug
)
Keyword search
self
.
keyword
=
self
.
request
.
GET
.
get
(
'q'
,
''
)
if
self
.
keyword
:
queryset
=
queryset.
filter
(
Q
(
title__icontains
=
self
.
keyword
)
|
Q
(
summary__icontains
=
self
.
keyword
)
)
return
queryset
def
get_context_data
(
self
,
**kwargs
)
:
"""Override the context method: inject extra data into the template"""
context
=
super
(
)
.
get_context_data
(
**kwargs
)
context
[
'categories'
]
=
Category.
objects
.
all
(
)
context
[
'category_slug'
]
=
self
.
category_slug
context
[
'keyword'
]
=
self
.
keyword
context
[
'title'
]
=
'RUNOOB Blog - Home'
return
context
Compare the amount of code before and after refactoring: FBV about 40 lines → CBV about 30 lines, and the logic is clearly divided into different methods.
DetailView — detail page refactoring
Example
File path: blog/views.py, newly added
from
django.
views
.
generic
import
DetailView
class
PostDetailView
(
DetailView
)
:
"""Post detail page: inherit DetailView"""
model
=
Post
template_name
=
'blog/post_detail.html'
context_object_name
=
'post'
pk_url_kwarg: the parameter name for passing the primary key in the URL (default is pk, declared explicitly here)
pk_url_kwarg
=
'pk'
def
get_context_data
(
self
,
**kwargs
)
:
context
=
super
(
)
.
get_context_data
(
**kwargs
)
context
[
'title'
]
=
f
'{self.object.title} - RUNOOB Blog'
return
context
Update route configuration
The CBV route syntax differs slightly from FBV — you need to call .as_view()。
Example
File path: blog/urls.py
from
django.
urls
import
path
from
django.
contrib
.
auth
import
views
as
auth_views
from
.
import
views
urlpatterns
=
[
CBV: add .as_view() after the class to convert it into a view function
path
(
''
,
views.
PostListView
.
as_view
(
)
,
name
=
'index'
)
,
path
(
'post/int:pk/'
,
views.
PostDetailView
.
as_view
(
)
,
name
=
'post_detail'
)
,
Other views unchanged
path
(
'register/'
,
views.
register
,
name
=
'register'
)
,
path
(
'login/'
,
auth_views.
LoginView
.
as_view
(
template_name
=
'blog/login.html'
,
redirect_authenticated_user
=
True
)
,
name
=
'login'
)
,
path
(
'logout/'
,
auth_views.
LogoutView
.
as_view
(
)
,
name
=
'logout'
)
,
path
(
'post/int:pk/favorite/'
,
views.
toggle_favorite
,
name
=
'toggle_favorite'
)
,
]
Why does CBV use
.as_view()? Django's URL configuration expects a callable object (function)..as_view()Convert a class view into a callable object that conforms to the Django view function signature, internally responsible for automatically dispatching to the class's get() or post() method according to the HTTP method (GET/POST).
Common generic views overview
| Views | Default template name | Purpose |
|---|---|---|
| ListView | model name_list.html | Display a list of objects |
| DetailView | model name_detail.html | Display details of a single object |
| CreateView | model name_form.html | Create a new object (with form) |
| UpdateView | model name_form.html | Update an existing object |
| DeleteView | model name_confirm_delete.html | Confirm deletion of an object |
| TemplateView | Need to specify | Render a static template (no data query) |
Django's generic views cover about 80% of web development scenarios. When they don't meet your needs, fall back to FBV.
LoginRequiredMixin
CBV cannot use @login_required decorators (those are for functions); use LoginRequiredMixin。
Example
from
django.
contrib
.
auth
.
mixins
import
LoginRequiredMixin
from
django.
views
.
generic
import
ListView
class
FavoriteListView
(
LoginRequiredMixin
,
ListView
)
:
"""Favorite list: requires login to access"""
model
=
Post
template_name
=
'blog/favorites.html'
context_object_name
=
'posts'
ordering
=
[
'-created_at'
]
LoginRequiredMixin: unlogged users are automatically redirected to settings.LOGIN_URL
def
get_queryset
(
self
)
:
Only display the posts favorited by the current user
return
self
.
request
.
user
.
favorite_posts
.
all
(
)
.
order_by
(
'-created_at'
)
The inheritance order of Mixins is important:
LoginRequiredMixinmust be writtenListViewfirst. Python's multiple inheritance resolution order is from left to right; LoginRequiredMixin checks the login status first, and only after passing does it continue to execute the ListView logic.
When to use CBV and when to use FBV?
Rule of thumb:
- FBV: views with complex logic, many conditional branches, and non-standard flows (such as toggle_favorite)
- CBV: standard CRUD operations, views whose logic can be clearly split into get/post (such as list pages and detail pages)
Operations like toggle_favorite (favorite toggle) have simple logic but a flow different from conventional CRUD, so FBV is more suitable.
For standard data display pages like index and post_detail, CBV can significantly reduce boilerplate code.
Chapter Summary
In this chapter you learned the core usage of Django class-based views: ListView to display lists, DetailView to display details, get_queryset/get_context_data to customize queries and context, as_view() to enable in routes, and LoginRequiredMixin to replace login_required.
The refactored home page and detail pages have shorter code and a clearer structure.