Class-Based Views (CBVs) provide a structured, reusable, and scalable way to handle requests in Django. Instead of writing logic inside functions, CBVs encapsulate behavior inside Python classes.
A CBV inherits from Django’s base View class or one of its generic subclasses like TemplateView, ListView, etc.
# Import required Django classes
from django.http import HttpResponse
from django.views import View
# Define a class-based view
class MyView(View):
def get(self, request):
return HttpResponse("Hello, World!")
CBVs must be connected using the as_view() method which converts the class into a callable view.
# URL configuration for CBV
from django.urls import path
from .views import MyView
urlpatterns = [
path('hello/', MyView.as_view(), name='hello'),
]
# Render a template using TemplateView
from django.views.generic import TemplateView
class HomeView(TemplateView):
template_name = 'home.html'
When the browser hits the mapped URL, Django creates an instance of the CBV and executes the corresponding HTTP method such as get() or post().
Change the URL path or response message and observe how CBVs dynamically control request handling.
class DemoView(View):
def get(self, req):
return "Displaying Page"
def post(self, req):
return "Data Saved!"
Viewas_view()TemplateView with context dataListView and DetailView