Expert guide for implementing Django class-based views with reusable view logic, URL configuration, async support, and HTTP method handling
Expert guide for implementing Django class-based views (CBVs) with reusable view logic, inheritance patterns, and async support.
This skill helps you design and implement Django class-based views following Django 5.1+ best practices. It covers:
When the user requests help with Django class-based views, follow these steps:
**For template rendering:**
**For model-based views:**
**For redirects:**
**For custom logic:**
**Direct URLconf usage** (for simple attribute overrides):
```python
from django.urls import path
from django.views.generic import TemplateView
urlpatterns = [
path("about/", TemplateView.as_view(template_name="about.html")),
]
```
**Subclassed views** (for complex logic):
```python
from django.views.generic import TemplateView
class AboutView(TemplateView):
template_name = "about.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['custom_data'] = "value"
return context
from django.urls import path
from .views import AboutView
urlpatterns = [
path("about/", AboutView.as_view()),
]
```
**Synchronous handlers:**
```python
from django.views import View
from django.http import HttpResponse
class MyView(View):
def get(self, request, *args, **kwargs):
return HttpResponse("GET response")
def post(self, request, *args, **kwargs):
return HttpResponse("POST response")
def head(self, request, *args, **kwargs):
response = HttpResponse()
response['Last-Modified'] = "date"
return response
```
**Important:** All method handlers in a view class must be either all synchronous (`def`) or all asynchronous (`async def`). Mixing will raise `ImproperlyConfigured`.
For I/O-bound operations (database queries, external APIs, file operations):
```python
import asyncio
from django.http import HttpResponse
from django.views import View
class AsyncView(View):
async def get(self, request, *args, **kwargs):
# Perform async operations
await asyncio.sleep(1)
data = await self.fetch_data()
return HttpResponse(f"Result: {data}")
async def fetch_data(self):
# Async helper method
return "async data"
```
**Requirements:**
**Override attributes for simple customization:**
```python
class MyListView(ListView):
model = Book
template_name = "books/list.html"
context_object_name = "books"
paginate_by = 10
```
**Override methods for complex logic:**
```python
class MyListView(ListView):
model = Book
def get_queryset(self):
return super().get_queryset().filter(published=True)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['total_books'] = self.get_queryset().count()
return context
```
**Use mixins for reusable behavior:**
```python
from django.contrib.auth.mixins import LoginRequiredMixin
class ProtectedView(LoginRequiredMixin, TemplateView):
template_name = "protected.html"
login_url = "/login/"
```
For REST API endpoints with custom HTTP method support:
```python
from django.http import HttpResponse, JsonResponse
from django.views.generic import ListView
class BookListView(ListView):
model = Book
def head(self, *args, **kwargs):
last_book = self.get_queryset().latest("publication_date")
response = HttpResponse(
headers={
"Last-Modified": last_book.publication_date.strftime(
"%a, %d %b %Y %H:%M:%S GMT"
)
}
)
return response
def get(self, request, *args, **kwargs):
# Standard list view behavior
return super().get(request, *args, **kwargs)
```
**Example 1: Simple Template View**
```python
path("about/", TemplateView.as_view(template_name="about.html"))
class AboutView(TemplateView):
template_name = "about.html"
```
**Example 2: List View with Custom Query**
```python
class PublishedBooksView(ListView):
model = Book
template_name = "books/published.html"
def get_queryset(self):
return Book.objects.filter(published=True).order_by("-pub_date")
```
**Example 3: Async API View**
```python
class AsyncDataView(View):
async def get(self, request):
await asyncio.sleep(0.1) # Simulate I/O
return JsonResponse({"status": "success"})
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/django-class-based-views-guide/raw