Class-Based Views
- Learn how to use Django Class-Based Views to build reusable and scalable application views.
What are Class-Based Views?
Class-Based Views allow us to write views using Python classes instead of functions.
Why CBVs?
Reusable code
Less repetition (DRY principle)
Built-in features (forms, pagination, authentication)
Easier to extend using inheritance
Function-Based View vs Class-Based View
# Function-Based View
def my_view(request):
return HttpResponse("Hello")
# Class-Based View
from django.views import View
class MyView(View):
def get(self, request):
return HttpResponse("Hello")
Types of Class-Based Views
Base Views
Generic Views
Form Views
Authentication Views
Generic Views
Generic Views are pre-built CBVs that handle common tasks like:
Listing data
Showing details
Creating, updating, deleting records
They work mainly with Django Models.
Why Generic Views?
Without generic views, we repeat:
Querying database
Rendering templates
Handling forms
Generic views reduce this boilerplate.
Common Generic Views
Sample Model
models.py
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
course = models.CharField(max_length=50)
def __str__(self):
return self.name
1. ListView
Purpose
Displays multiple records from database.
Student ListView
views.py
from django.views.generic import ListView
from .models import Student
class StudentListView(ListView):
model = Student
template_name = 'students/student_list.html'
context_object_name = 'students'
Code Description
model → Database table
template_name → HTML file
context_object_name → Variable name in template
Template Example
student_list.html
<h2>Student List</h2>
{% for student in students %}
<p>{{ student.name }} - {{ student.course }}</p>
{% endfor %}
2. DetailView
Purpose
Shows single record details.
Student DetailView
views.py
from django.views.generic import DetailView
from .models import Student
class StudentDetailView(DetailView):
model = Student
template_name = 'students/student_detail.html'
URL Configuration
urls.py
from django.urls import path
from .views import StudentDetailView
urlpatterns = [
path('student/<int:pk>/', StudentDetailView.as_view(), name='student_detail'),
]
Key Concept
pk → Primary Key
Django automatically fetches object
3. CreateView
Purpose
Handles form + save logic automatically.
Student CreateView
views.py
from django.views.generic import CreateView
from .models import Student
class StudentCreateView(CreateView):
model = Student
fields = ['name', 'email', 'course']
template_name = 'students/student_form.html'
success_url = '/students/'
4. UpdateView
Purpose
Edit existing records.
Student UpdateView
# views.py
from django.views.generic import UpdateView
class StudentUpdateView(UpdateView):
model = Student
fields = ['name', 'email', 'course']
template_name = 'students/student_form.html'
success_url = '/students/'
5. DeleteView
Purpose
Delete records with confirmation.
Student DeleteView
views.py
from django.views.generic import DeleteView
class StudentDeleteView(DeleteView):
model = Student
template_name = 'students/student_confirm_delete.html'
success_url = '/students/'
What are Mixins?
Mixins are small reusable classes that add extra functionality to CBVs.
They do one job only and are combined with CBVs.
Why Mixins?
Add authentication
Add permissions
Share logic
Avoid duplication
Common Django Mixins
1. LoginRequiredMixin
Purpose
Restrict view to logged-in users only.
Login Required ListView
views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView
class SecureStudentListView(LoginRequiredMixin, ListView):
model = Student
template_name = 'students/student_list.html'
login_url = '/login/'
Important Rule
Mixin must come before Generic View
✅ Correct:
class MyView(LoginRequiredMixin, ListView):
❌ Wrong:
class MyView(ListView, LoginRequiredMixin):
2. PermissionRequiredMixin
Purpose
Restrict access based on user permissions.
Permission Based View
from django.contrib.auth.mixins import PermissionRequiredMixin
class StudentCreatePermissionView(PermissionRequiredMixin, CreateView):
model = Student
fields = ['name', 'email', 'course']
permission_required = 'app.add_student'
3. UserPassesTestMixin
Purpose
Custom logic for access control.
Custom Role Check
from django.contrib.auth.mixins import UserPassesTestMixin
class AdminOnlyView(UserPassesTestMixin, ListView):
model = Student
def test_func(self):
return self.request.user.is_superuser
Custom Mixin for Common Context
mixins.py
class CourseTitleMixin:
course_title = "Django Advanced Course"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['course_title'] = self.course_title
return context