Learn / Frameworks / Django / Class-Based Views

Django · Lesson 7 of 15

Class-Based Views

ListView, DetailView, CreateView and mixins instead of long function views.

  • Intermediate
  • 16 min read
  • 3 objectives

Before this lessonLesson 6: Users, Login and Permissions

What you will learn

  • Write a ListView
  • Use a CreateView
  • Add a mixin

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Function views are explicit. Class-based views (CBVs) reuse the boring bits: fetch an object, paginate a list, validate a form, redirect on success.

List and detail

from django.views.generic import ListView, DetailView
from .models import Post

class PostList(ListView):
    model = Post
    paginate_by = 20
    queryset = Post.objects.filter(published=True).order_by("-created")
    context_object_name = "posts"      # otherwise it is object_list

class PostDetail(DetailView):
    model = Post
    slug_field = "slug"

Create, update, delete

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy

class PostCreate(LoginRequiredMixin, CreateView):
    model = Post
    fields = ["title", "body"]
    success_url = reverse_lazy("post-list")

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

When a function is clearer

If you override three methods to fight the CBV, write a function. Mixins shine when you reuse the same access rule across many views.

Up next · Lesson 8The ORM in Depthselect_related, aggregations, F expressions, transactions and indexes.