← Back to Chapters

Class-Based Views (CBVs)

? Class-Based Views (CBVs)

✨ Quick Overview

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.

? Key Concepts

  • Views are written as Python classes
  • Each HTTP method maps to a class method
  • Highly reusable and extendable
  • Built-in generic views reduce boilerplate

? Syntax / Theory

A CBV inherits from Django’s base View class or one of its generic subclasses like TemplateView, ListView, etc.

Basic Structure of a CBV

? View Code Example
# 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!")

? Mapping CBVs to URLs

CBVs must be connected using the as_view() method which converts the class into a callable view.

? View Code Example
# URL configuration for CBV
from django.urls import path
from .views import MyView

urlpatterns = [
    path('hello/', MyView.as_view(), name='hello'),
]

? Built-In Generic Class-Based Views

  • TemplateView – Render static templates
  • ListView – Display lists of objects
  • DetailView – Show object details
  • CreateView – Create new objects
  • UpdateView – Update objects
  • DeleteView – Delete objects

TemplateView Example

? View Code Example
# Render a template using TemplateView
from django.views.generic import TemplateView

class HomeView(TemplateView):
    template_name = 'home.html'

? Live Output / Explanation

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().

? Interactive Example

Change the URL path or response message and observe how CBVs dynamically control request handling.

Python Logic (View):
class DemoView(View):
  def get(self, req):
    return "Displaying Page"
    
  def post(self, req):
    return "Data Saved!"
Server Response:
Click "Send Request"

? Use Cases

  • Large applications with repeated logic
  • CRUD operations
  • Dashboard and admin panels
  • REST-style structured views

? Tips & Best Practices

  • Use CBVs for reusable patterns
  • Prefer generic views when possible
  • Override only what you need
  • Keep views thin, logic in models

? Try It Yourself

  • Create a CBV using View
  • Map it with as_view()
  • Extend TemplateView with context data
  • Experiment with ListView and DetailView