Class-based views (CBVs) in Django hide control flow behind inheritance chains, so I stick to four generic views that match standard pages: ListView, DetailView, TemplateView, and FormView.
Generic Views That Cut Boilerplate
Public pages on this portfolio follow three shapes:
ListViewfor collections: I useProjectListViewandBlogListViewfor queryset filtering, search queries, and pagination without hand-writing page math.DetailViewfor slug lookups: I useProjectDetailViewandPostDetailViewto resolve<slug:slug>and return a404for missing records or unpublished drafts.FormViewfor validated POST workflows: I useBriefPageViewto render the contact form, bindaria-describedbyerror hooks on invalid input, and redirect after a valid POST so a browser refresh does not send a duplicate message.
class PostDetailView(DetailView):
template_name = "core/post_detail.html"
context_object_name = "post"
def get_queryset(self):
# Drafts must 404, not leak via direct URL.
return Post.objects.filter(published=True)
Plain Function Views
Generic views get in the way on non-template endpoints. For JSON handlers like brief_submit, plain text like robots_txt, or file streaming in media_file, I write a Python function with @require_GET or @require_POST so you can read it top to bottom.
Reach for a generic CBV to remove repeated queryset, pagination, or form code. Switch to a function view the moment you fight its lifecycle methods.