Class-Based Views

A view written as a Python class instead of a function. Django provides built-in classes that help reduce repetitive code and make views more reusable.

CBVs are commonly used in medium and large Django applications.

Why Use Class-Based Views?

Function-Based Views work well for simple tasks, but as applications grow, code duplication increases.

CBVs provide:

  • Better code reusability
  • Cleaner structure
  • Built-in functionality
  • Easy extension through inheritance

Creating a Basic Class-Based View

views.py

from django.http import HttpResponse
from django.views import View

class HomeView(View):

    def get(self, request):
        return HttpResponse("Welcome to Django CBV")

urls.py

from django.urls import path
from .views import HomeView

urlpatterns = [
    path('', HomeView.as_view()),
]

Output

Welcome to Django CBV

Understanding as_view()

path('', HomeView.as_view())

as_view() converts the class into a callable view that Django can execute.

Without as_view(), Django cannot process the class.

Handling GET Requests

from django.views import View
from django.http import HttpResponse

class HomeView(View):

    def get(self, request):
        return HttpResponse("GET Request")

When the browser requests a page, Django automatically calls the get() method.

Handling POST Requests

from django.views import View
from django.http import HttpResponse

class HomeView(View):

    def get(self, request):
        return HttpResponse("GET Request")

    def post(self, request):
        return HttpResponse("POST Request")

Django automatically executes:

  • get() for GET requests
  • post() for POST requests
  • put() for PUT requests
  • delete() for DELETE requests

Using Templates with CBV

from django.views import View
from django.shortcuts import render

class HomeView(View):

    def get(self, request):
        return render(request, 'home.html')

home.html

<h1>Welcome to Django</h1>

Passing Data to Templates

from django.views import View
from django.shortcuts import render

class HomeView(View):

    def get(self, request):
        context = {
            'name': 'Tarun',
            'course': 'Django'
        }
        return render(request, 'home.html', context)

home.html

<h1>{{ name }}</h1>
<p>{{ course }}</p>

Built-in Generic Views

Django provides many ready-made CBVs.

Examples:

  • ListView
  • DetailView
  • CreateView
  • UpdateView
  • DeleteView
  • TemplateView

These views help reduce boilerplate code.

Example: TemplateView

from django.views.generic import TemplateView

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

Function-Based View vs Class-Based View

Function-Based ViewClass-Based View
Uses functionsUses classes
Easy to learnMore powerful
Less reusableHighly reusable
Better for simple logicBetter for complex logic
More code repetitionLess code repetition

When to Use CBV?

Use CBVs when:

  • Building large applications
  • Reusing view logic
  • Working with CRUD operations
  • Using Django Generic Views