Class-Based Views (CBVs) provide a structured way to organize view logic in Django. While CBVs offer many built-in methods for handling HTTP requests and responses, there are times when you may need to modify or extend the default behavior.
super()
# Adding extra context data to template
from django.views.generic import DetailView
from .models import Book
class BookDetailView(DetailView):
model = Book
template_name = 'book_detail.html'
context_object_name = 'book'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['additional_info'] = "Some additional context data"
return context
# Filtering queryset based on condition
from django.views.generic import ListView
from .models import Book
class BookListView(ListView):
model = Book
template_name = 'book_list.html'
context_object_name = 'books'
def get_queryset(self):
return Book.objects.filter(pages__gt=100)
# Custom action before saving form
from django.views.generic.edit import CreateView
from .models import Book
class BookCreateView(CreateView):
model = Book
template_name = 'book_form.html'
fields = ['title', 'author', 'price']
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
Each overridden method allows you to inject custom logic while still leveraging Django’s built-in workflow. Using super() ensures the framework continues to handle routing, rendering, and validation correctly.
Click a button to simulate how Django processes data when you override specific methods.
super() unless intentionally replacing behaviorget_queryset() using request parametersform_valid()get_context_data()