</>
Skip to content
Django lessons (33/43)

Django — Class-Based Views

Basic CBV

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

class MyView(View):
    def get(self, request):
        return HttpResponse("GET request")
    
    def post(self, request):
        return HttpResponse("POST request")

URL Pattern

from django.urls import path
from .views import MyView

urlpatterns = [
    path('my-view/', MyView.as_view(), name='my-view'),
]

Generic Views

from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post

class PostListView(ListView):
    model = Post
    template_name = 'blog/list.html'
    context_object_name = 'posts'
    paginate_by = 10

class PostDetailView(DetailView):
    model = Post
    template_name = 'blog/detail.html'
    context_object_name = 'post'

class PostCreateView(CreateView):
    model = Post
    template_name = 'blog/form.html'
    fields = ['title', 'content']
    success_url = '/blog/'

class PostUpdateView(UpdateView):
    model = Post
    template_name = 'blog/form.html'
    fields = ['title', 'content']

class PostDeleteView(DeleteView):
    model = Post
    template_name = 'blog/confirm_delete.html'
    success_url = '/blog/'

Mixins

from django.contrib.auth.mixins import LoginRequiredMixin

class ProtectedView(LoginRequiredMixin, View):
    login_url = '/login/'
    redirect_field_name = 'redirect_to'

Mini Practice

  1. Create a basic CBV
  2. Use generic views for CRUD
  3. Apply mixins for authentication
  4. Customize generic views

Up Next

Continue with Generic Views — built-in generic views.

Related Topics

Frequently Asked Questions about Class-Based Views

What is Class-Based Views in Django?

Class-Based Views is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Class-Based Views?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Class-Based Views.

Why is Class-Based Views important in Django?

Class-Based Views is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.