python / intermediate
Snippet
Django Generic Class-Based Views: ListView and DetailView
Django's generic class-based views provide pre-built functionality for common patterns. ListView handles pagination and object listing, while DetailView looks up objects by slug or pk. LoginRequiredMixin adds authentication protection. These reduce boilerplate significantly.
snippet.py
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
# views.pyfrom django.views.generic import ListView, DetailViewfrom django.contrib.auth.mixins import LoginRequiredMixinfrom .models import Postclass PostListView(LoginRequiredMixin, ListView):model = Posttemplate_name = 'blog/post_list.html'context_object_name = 'posts'paginate_by = 10def get_queryset(self):return Post.objects.filter(author=self.request.user).order_by('-created')class PostDetailView(DetailView):model = Posttemplate_name = 'blog/post_detail.html'context_object_name = 'post'slug_field = 'slug'query_pk_and_slug = True# urls.pypath('posts/', PostListView.as_view(), name='post_list'),path('post/<slug:slug>/', PostDetailView.as_view(), name='post_detail'),
django
Breakdown
1
class PostListView(LoginRequiredMixin, ListView):
Multiple inheritance: LoginRequiredMixin checks auth first, then ListView provides list functionality
2
paginate_by = 10
Automatically splits querysets into pages of 10 items each
3
def get_queryset(self):
Override to filter posts to only those authored by the current user
4
query_pk_and_slug = True
Allows DetailView to lookup by either primary key or slug field
5
PostDetailView.as_view()
Converts the class into a callable view function for URL routing