MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Class-Based Views (CBV)0%
Study Materials
Django for Backend DevelopmentProgress 0%
1.1Installing Django & Environment Setup1.2Django Project Structure1.3Creating First Django App
5.1Function-Based Views (FBV)5.2Class-Based Views (CBV)5.3URL Dispatcher and Routing
HomeTutorialsDjango for Backend DevelopmentClass-Based Views (CBV)
URL Dispatcher and Routing

Class-Based Views (CBV)

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

While Function-Based Views are simple and explicit, standard web applications contain repetitive CRUD operations: listing records, displaying details, creating records via forms, updating instances, and deleting rows. Django's Class-Based Views (CBVs) and Generic Class-Based Views (GCBVs) use object-oriented patterns, mixins, and inheritance to eliminate hundreds of lines of boilerplate.


1. The Class-Based View Hierarchy

1View (Base Class)
2 └── TemplateView (Renders static template)
3 └── RedirectView (Handles HTTP redirects)
4 └── DetailView (Fetches single object by pk/slug)
5 └── ListView (Fetches paginated list of objects)
6 └── FormView (Validates arbitrary form)
7 └── CreateView (Validates ModelForm and saves new instance)
8 └── UpdateView (Validates ModelForm and updates existing instance)
9 └── DeleteView (Handles confirmation and deletes instance)

2. Implementing Standard CRUD with Generic Views

1# articles/views.py
2from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
3from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
4from django.urls import reverse_lazy
5from .models import Article
6 
7# 1. LIST: Paginated Article Directory
8class ArticleListView(ListView):
9 model = Article
10 template_name = "articles/article_list.html"
11 context_object_name = "articles"
12 paginate_by = 10
13 
14 def get_queryset(self):
15 # Override query to return only published articles
16 return Article.objects.filter(status="published").select_related("author")
17 
18# 2. DETAIL: Single Article View
19class ArticleDetailView(DetailView):
20 model = Article
21 template_name = "articles/article_detail.html"
22 context_object_name = "article"
23 slug_field = "slug"
24 slug_url_kwarg = "slug"
25 
26# 3. CREATE: Form Generation & Persistence
27class ArticleCreateView(LoginRequiredMixin, CreateView):
28 model = Article
29 fields = ["title", "content", "category", "tags", "status"]
30 template_name = "articles/article_form.html"
31 
32 def form_valid(self, form):
33 # Automatically inject authenticated user as author
34 form.instance.author = self.request.user
35 return super().form_valid(form)
36 
37# 4. UPDATE: Guarded by Author Ownership
38class ArticleUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
39 model = Article
40 fields = ["title", "content", "category", "status"]
41 template_name = "articles/article_form.html"
42 
43 # Authorization guard: only author can edit!
44 def test_func(self):
45 article = self.get_object()
46 return self.request.user == article.author
47 
48# 5. DELETE: Confirmation & Teardown
49class ArticleDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
50 model = Article
51 template_name = "articles/article_confirm_delete.html"
52 success_url = reverse_lazy("articles:list")
53 
54 def test_func(self):
55 article = self.get_object()
56 return self.request.user == article.author

3. Connecting CBVs in urls.py with as_view()

URL dispatchers expect a callable function. CBVs provide the .as_view() class method to generate the callable:

1# articles/urls.py
2from django.urls import path
3from .views import (
4 ArticleListView,
5 ArticleDetailView,
6 ArticleCreateView,
7 ArticleUpdateView,
8 ArticleDeleteView,
9)
10 
11app_name = "articles"
12 
13urlpatterns = [
14 path("", ArticleListView.as_view(), name="list"),
15 path("create/", ArticleCreateView.as_view(), name="create"),
16 path("<slug:slug>/", ArticleDetailView.as_view(), name="detail"),
17 path("<slug:slug>/edit/", ArticleUpdateView.as_view(), name="edit"),
18 path("<slug:slug>/delete/", ArticleDeleteView.as_view(), name="delete"),
19]

4. Why reverse_lazy is Required in Class Attributes

In class definitions, class attributes (success_url = reverse_lazy('...')) are evaluated when the Python module is first imported. Standard reverse() fails because URL patterns haven't finished loading yet. reverse_lazy() defers evaluation until the URL is actually accessed!


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What method must always be called when registering a Class-Based View in urls.py?
Question 2
What mixin is used in CBVs to require that a user be logged in, equivalent to the @login_required decorator?
Question 3
Why is reverse_lazy() used for success_url class attributes instead of standard reverse()?
Question 4
How does UserPassesTestMixin enforce custom authorization rules on a CBV?
Question 5
In a CreateView, how do you inject the current logged-in user as the model author before saving?
Next Lesson

URL Dispatcher and Routing

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Function-Based Views (FBV)URL Dispatcher and Routing

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Django for Backend Development with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext