Skip to main content
Course/Module 4/Topic 2 of 5Intermediate

Class-Based Views

Explore Django's class-based views for reusable, object-oriented web request handling.

65 minBy Priygop TeamLast updated: Feb 2026

Class-Based Views (CBVs)

Class-based views provide an object-oriented way to organize code and reuse functionality. They're more powerful and flexible than function-based views.

Common CBVs

Example
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from .models import Post, Category
from .forms import PostForm

# List View
class PostListView(ListView):
    model = Post
    template_name = 'blog/post_list.html'
    context_object_name = 'posts'
    paginate_by = 10
    ordering = ['-published_date']
    
    def get_queryset(self):
        """Filter to only published posts"""
        return Post.objects.filter(published_date__isnull=False)
    
    def get_context_data(self, **kwargs):
        """Add extra context data"""
        context = super().get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        return context

# Detail View
class PostDetailView(DetailView):
    model = Post
    template_name = 'blog/post_detail.html'
    context_object_name = 'post'
    
    def get_object(self):
        """Get the post or return 404"""
        return get_object_or_404(Post, pk=self.kwargs['pk'])

# Create View
class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    form_class = PostForm
    template_name = 'blog/post_form.html'
    success_url = reverse_lazy('post_list')
    
    def form_valid(self, form):
        """Set the author before saving"""
        form.instance.author = self.request.user
        return super().form_valid(form)

# Update View
class PostUpdateView(LoginRequiredMixin, UpdateView):
    model = Post
    form_class = PostForm
    template_name = 'blog/post_form.html'
    
    def get_success_url(self):
        """Redirect to the updated post"""
        return reverse_lazy('post_detail', kwargs={'pk': self.object.pk})

# Delete View
class PostDeleteView(LoginRequiredMixin, DeleteView):
    model = Post
    template_name = 'blog/post_confirm_delete.html'
    success_url = reverse_lazy('post_list')

# Custom CBV with mixins
from django.contrib.auth.mixins import UserPassesTestMixin

class UserPostListView(LoginRequiredMixin, ListView):
    model = Post
    template_name = 'blog/user_posts.html'
    context_object_name = 'posts'
    
    def get_queryset(self):
        """Show only user's posts"""
        return Post.objects.filter(author=self.request.user)

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    form_class = PostForm
    template_name = 'blog/post_form.html'
    
    def test_func(self):
        """Check if user is the author of the post"""
        post = self.get_object()
        return self.request.user == post.author

Additional Resources

Recommended Reading

  • Django Views Documentation
  • Django Templates Documentation
  • Django CBV by Classy Class-Based Views

Online Resources

  • Django Template Language
  • Django Generic Views
  • Template Tags and Filters
Chat on WhatsApp
Priygop - Leading Professional Development Platform | Expert Courses & Interview Prep