Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Class-Based Views (CBVs) Introduction
Class-Based Views (CBVs) use Python classes instead of functions. They provide built-in methods for common patterns (list, detail, create, update, delete) and support inheritance for code reuse. CBVs are more structured but have a steeper learning curve.
CBV Basics
- CBVs use Python classes with methods like get(), post(), put()
- View - Base class for all CBVs
- TemplateView - Render a template with context
- ListView - Display a list of objects
- DetailView - Display a single object
- CreateView, UpdateView, DeleteView - CRUD operations
- Use .as_view() in urls.py to convert class to view function
- CBVs promote DRY - inherit and override instead of rewriting
CBV Examples
# blog/views.py
# from django.views import View
# from django.views.generic import TemplateView, ListView, DetailView
# from .models import Post
# Basic CBV with get/post methods
# class HomeView(View):
# def get(self, request):
# return render(request, 'blog/home.html')
# def post(self, request):
# # Handle form submission
# return redirect('home')
# TemplateView - simplest CBV
# class AboutView(TemplateView):
# template_name = 'blog/about.html'
# ListView - list of objects
# class PostListView(ListView):
# model = Post
# template_name = 'blog/list.html'
# context_object_name = 'posts'
# ordering = ['-created_at']
# paginate_by = 10
# DetailView - single object
# class PostDetailView(DetailView):
# model = Post
# template_name = 'blog/detail.html'
# context_object_name = 'post'
# blog/urls.py
# urlpatterns = [
# path('', PostListView.as_view(), name='post-list'),
# path('<int:pk>/', PostDetailView.as_view(), name='post-detail'),
# path('about/', AboutView.as_view(), name='about'),
# ]Tip
Tip
Always review migration files before applying. Use --dry-run with squashmigrations to preview. Never edit applied migrations.
QuerySets are LAZY - no DB hit until evaluated.
Common Mistake
Warning
Deleting migration files to fix issues. This corrupts migration history. Use squashmigrations or data migrations instead.
Practice Task
Note
(1) Make a model change and create a migration. (2) Review the SQL with sqlmigrate. (3) Apply with migrate.
Quick Quiz
Key Takeaways
- Class-Based Views (CBVs) use Python classes instead of functions.
- CBVs use Python classes with methods like get(), post(), put()
- View - Base class for all CBVs
- TemplateView - Render a template with context