📝 Django

Class-Based Views in Django

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
80
🌿
Level
Medium

CBVs use classes instead of functions. The built-in CBVs implement common CRUD patterns.

ListView

# views.py
from django.views.generic import ListView
from .models import Task

class TaskListView(ListView):
    model = Task
    template_name = 'tasks/list.html'   # default: tasks/task_list.html
    context_object_name = 'tasks'        # variable name in the template
    paginate_by = 10                     # pagination

    def get_queryset(self):
        return Task.objects.filter(status='todo').order_by('-created_at')
# urls.py
path('', TaskListView.as_view(), name='task-list'),

DetailView

from django.views.generic import DetailView

class TaskDetailView(DetailView):
    model = Task
    template_name = 'tasks/detail.html'
    context_object_name = 'task'
    pk_url_kwarg = 'pk'   # URL parameter name

CreateView

from django.views.generic.edit import CreateView
from django.urls import reverse_lazy

class TaskCreateView(CreateView):
    model = Task
    fields = ['title', 'description', 'status', 'priority']
    template_name = 'tasks/form.html'
    success_url = reverse_lazy('task-list')

The template must contain {{ form }} and {% csrf_token %}.

UpdateView

from django.views.generic.edit import UpdateView

class TaskUpdateView(UpdateView):
    model = Task
    fields = ['title', 'description', 'status']
    template_name = 'tasks/form.html'
    success_url = reverse_lazy('task-list')

DeleteView

from django.views.generic.edit import DeleteView

class TaskDeleteView(DeleteView):
    model = Task
    template_name = 'tasks/confirm_delete.html'
    success_url = reverse_lazy('task-list')

URLs for All CBVs

urlpatterns = [
    path('', TaskListView.as_view(), name='task-list'),
    path('<int:pk>/', TaskDetailView.as_view(), name='task-detail'),
    path('create/', TaskCreateView.as_view(), name='task-create'),
    path('<int:pk>/edit/', TaskUpdateView.as_view(), name='task-edit'),
    path('<int:pk>/delete/', TaskDeleteView.as_view(), name='task-delete'),
]

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

Event Loop in Python: How asyncio Achieves "Paral…

Event loop is the heart of asyncio. It doesn't run code in parallel across multiple...

📅 30.06.2026 👁️ 122
📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 131
📝

Django: Template Tags

Template tags are logic inside HTML. Unlike {{ variable }} which only outputs a value,...

📅 30.06.2026 👁️ 81

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!