In Django, a class-based view (CBV) provides an alternative to function-based views (FBVs) by allowing you to use classes and inheritance to organize your code. CBVs offer greater flexibility and reusability compared to FBVs. Below, I’ll provide an overview of how to create and use class-based views in Django.
Creating a Class-Based View
- Import the necessary modules:
from django.views import View from django.http import HttpResponse
- Define your class-based view:
class MyView(View): def get(self, request): return HttpResponse('Hello, this is a class-based view!')
- Map the view to a URL in your
urls.py
:from django.urls import path from .views import MyView urlpatterns = [ path('myview/', MyView.as_view(), name='myview'), ]
Types of Class-Based Views
Django provides several built-in class-based views for common use cases, such as:
- TemplateView: Renders a template.
- ListView: Displays a list of objects.
- DetailView: Displays a detail page for a single object.
- CreateView: Handles object creation.
- UpdateView: Handles object updates.
- DeleteView: Handles object deletion.
References
https://docs.djangoproject.com/en/5.0/topics/class-based-views/