Class-Based Views (CBVs) are a powerful feature in Django that allow you to organize your views as Python classes rather than functions. This approach improves modularity, reuse, and maintainability, especially in large or complex applications.
# CBV for listing books using Django ListView
from django.views.generic import ListView
from .models import Book
class BookListView(ListView):
model = Book
template_name = 'book_list.html'
context_object_name = 'books'
# URL configuration for BookListView
from django.urls import path
from .views import BookListView
urlpatterns = [
path('books/', BookListView.as_view(), name='book_list'),
]
The BookListView automatically fetches all Book objects and sends them to the template as books. The as_view() method converts the class into a callable view.
Think of CBVs as Lego blocks: Django provides ready-made blocks (generic views), and you only customize the pieces you need. Use the generator below to see how changing parameters changes the code.
get_queryset() for filtering.get_context_data() for extra template data.DetailView for a model.get_context_data().CreateView.