Chapter 11 · 10 min read
Class-based and Generic Views
Class-based and Generic Views
You have written views as functions. Django also lets you write them as classes, and it ships generic views that already do the common jobs: list objects, show one, create, edit and delete. In this chapter you will replace your function views with generic views and add rules about who may use them.
What you will learn
- The difference between function-based and class-based views.
- How to use
ListView,DetailView,CreateViewandUpdateView. - How the naming conventions let you skip most code.
- How to restrict access with
LoginRequiredMixinandUserPassesTestMixin.
Two styles, both normal
| Task | Function-based view | Class-based generic view |
|---|---|---|
| Show a list | Query, then render() | ListView with model or queryset |
| Show one item | get_object_or_404(), then render() | DetailView with model |
| Create | GET/POST branching, form.save() | CreateView with form_class |
| Edit | Same, with an instance | UpdateView |
| Requires login | @login_required | LoginRequiredMixin |
Function views are explicit and easy to read when you start. Generic views remove repetition once you know the pattern. Most real projects use both.
Naming conventions
Generic views follow rules that you can rely on.
| View | Template it looks for | Context variables |
|---|---|---|
ListView of Post | blog/post_list.html | post_list and object_list |
DetailView of Post | blog/post_detail.html | post and object |
CreateView / UpdateView | blog/post_form.html | form |
The pattern is <app>/<model>_<suffix>.html. You can override any of it with attributes such as template_name, but you rarely need to. This is why your templates from earlier chapters will keep working.
Step by step
1. The views
Replace blog/views.py:
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import CreateView, DetailView, ListView, UpdateView
from .forms import PostForm
from .models import Post
class PostListView(ListView):
model = Post
queryset = Post.objects.filter(published=True).select_related("author")
class PostDetailView(DetailView):
model = Post
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
form_class = PostForm
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
form_class = PostForm
def test_func(self):
return self.get_object().author == self.request.user
Walkthrough:
PostListViewneeds only the model. Settingquerysetnarrows which rows are shown.PostDetailViewfinds the object using thepkcaptured in the URL.PostCreateViewshows the form on GET and saves on POST. After saving it redirects to the object'sget_absolute_url(), which is why you defined that method.form_valid()is the hook that runs when the form is valid; you set the author there and callsuper()to finish the job.PostUpdateViewedits an existing post.LoginRequiredMixindemands a logged-in user.UserPassesTestMixincallstest_func(); if it returnsFalse, the visitor gets403 Forbidden. Here only the author passes.- The order of the parents matters: mixins come first, the generic view last.
2. The URLs
Replace blog/urls.py:
from django.urls import path
from . import views
app_name = "blog"
urlpatterns = [
path("", views.PostListView.as_view(), name="home"),
path("post/new/", views.PostCreateView.as_view(), name="create"),
path("post/<int:pk>/", views.PostDetailView.as_view(), name="detail"),
path("post/<int:pk>/edit/", views.PostUpdateView.as_view(), name="edit"),
]
as_view() turns the class into a callable that path() can use. Forgetting the parentheses is a classic error.
3. An edit link
In post_detail.html, add this just before {% endblock %}:
{% if user == post.author %}
<p><a href="{% url 'blog:edit' post.pk %}">Edit this post</a></p>
{% endif %}
How a class-based view works inside
When a request arrives, as_view() creates an instance of your class and calls dispatch(), which calls the method named after the HTTP verb: get() or post(). Generic views implement these and break them into small methods you can override, such as get_queryset(), get_context_data(), form_valid() and get_success_url(). Customising means overriding one small method, not rewriting everything.
class MyPostsView(LoginRequiredMixin, ListView):
model = Post
def get_queryset(self):
return Post.objects.filter(author=self.request.user)
Check it works
- The home page, detail page and
/post/new/behave exactly as before. - As the author,
/post/1/edit/opens the form filled with the post. - Logged in as a different user, the same address shows
403 Forbidden.
Exercises with solutions
Exercise 1: delete view
Add PostDeleteView so authors can delete their posts.
Solution.
from django.urls import reverse_lazy
from django.views.generic import DeleteView
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Post
success_url = reverse_lazy("blog:home")
def test_func(self):
return self.get_object().author == self.request.user
URL: path("post/<int:pk>/delete/", views.PostDeleteView.as_view(), name="delete"),. Template blog/post_confirm_delete.html:
{% extends "blog/base.html" %}
{% block content %}
<h1>Delete this post?</h1>
<p>{{ object.title }}</p>
<form method="post">
{% csrf_token %}
<button type="submit">Yes, delete</button>
<a href="{{ object.get_absolute_url }}">Cancel</a>
</form>
{% endblock %}
reverse_lazy is needed because the URLs are not loaded yet when the class body runs.
Exercise 2: my posts
Show only the logged-in user's posts, including drafts, at /mine/.
Solution. Use the MyPostsView shown above and map it with path("mine/", views.MyPostsView.as_view(), name="mine"). It reuses post_list.html because the model and suffix match.
Exercise 3: change the template
Make PostListView use a template called blog/home.html instead of the default.
Solution. Add the attribute template_name = "blog/home.html". Any generic view accepts template_name.
Common mistakes
- Forgetting
.as_view()inurls.py. - Putting mixins after the view class.
LoginRequiredMixinmust come beforeCreateView. - Leaving out
form_valid. Saving fails because the author is missing. - Template name mismatch. The default is
<app>/<model>_<suffix>.html. - No
get_absolute_urlon the model and nosuccess_url. Django cannot decide where to redirect. - Using
reverseinstead ofreverse_lazyfor class attributes.
Key takeaways
- Generic views encode Django's most common patterns; learn their names and hooks.
- Naming conventions pick templates and context variable names automatically.
- Mixins such as
LoginRequiredMixinadd behaviour; list them before the view class. - Override small methods like
get_querysetandform_validto customise.
Official links
- Class-based views: https://docs.djangoproject.com/en/6.1/topics/class-based-views/
- Generic view reference: https://docs.djangoproject.com/en/6.1/ref/class-based-views/
