Class-Based Views
CBVs organize view logic into reusable classes instead of functions.
Syntax
path("", MyView.as_view())Class-based views (CBVs) let you build views from classes, keeping related behavior together and letting you reuse logic through inheritance and mixins. Django ships many generic views for common tasks.
Wire a CBV into your URLconf with .as_view().
Example
# blog/views.py
from django.views import View
from django.http import HttpResponse
class HomeView(View):
def get(self, request):
return HttpResponse("Hello from a class-based view")
# blog/urls.py
# path("", HomeView.as_view(), name="home")When to use it
- A developer replaces a repetitive function-based view with a class-based view to reuse logic across multiple views.
- A team uses CBVs to share authentication checks via a LoginRequiredMixin applied to many views at once.
- A developer uses View to handle GET and POST in separate methods instead of a single if/else block.
More examples
Simplest class-based view
Subclasses the base View class and defines a get() method to handle HTTP GET requests.
from django.views import View
from django.http import HttpResponse
class HomeView(View):
def get(self, request):
return HttpResponse("Hello from CBV!")Wire CBV to a URL
Uses as_view() to convert the class into a callable view function for the URLconf.
from django.urls import path
from .views import HomeView
urlpatterns = [
path("", HomeView.as_view(), name="home"),
]Handle GET and POST separately
Separates GET (show form) and POST (process form) into clean, distinct methods.
class ContactView(View):
def get(self, request):
form = ContactForm()
return render(request, "contact.html", {"form": form})
def post(self, request):
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return redirect("thanks")
return render(request, "contact.html", {"form": form})
Discussion