0 day streak
python / intermediate
Snippet

Django Class-Based Views with TemplateResponse

Class-Based Views (CBVs) in Django provide reusable, modular view components. ListView automatically handles pagination and template rendering for lists of objects. DetailView provides a clean way to display single objects by slug or primary key. LoginRequiredMixin adds authentication protection. The get_queryset() method allows dynamic filtering based on URL parameters or query strings.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from django.views.generic import ListView, DetailView
from django.shortcuts import get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Book, Category
class BookListView(LoginRequiredMixin, ListView):
model = Book
template_name = 'books/book_list.html'
context_object_name = 'books'
paginate_by = 10
def get_queryset(self):
queryset = Book.objects.filter(is_published=True)
category = self.request.GET.get('category')
if category:
queryset = queryset.filter(category__slug=category)
return queryset.order_by('-published_date')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['categories'] = Category.objects.all()
return context
class BookDetailView(DetailView):
model = Book
template_name = 'books/book_detail.html'
context_object_name = 'book'
slug_field = 'slug'
slug_url_kwarg = 'slug'
django
Breakdown
1
class BookListView(LoginRequiredMixin, ListView):
CBV combining authentication mixin with generic ListView functionality
2
paginate_by = 10
Django automatically paginates results, passing page object to template
3
def get_queryset(self):
Override to customize which objects are retrieved, with optional filtering
4
slug_field = 'slug'
DetailView uses the slug field to look up the Book instance