๐Ÿ“ Django

Mixins in Django CBV

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
276
๐ŸŒณ
Level
Advanced

Mixins are small classes that add a single behavior to CBVs through multiple inheritance.

Built-in Mixins

LoginRequiredMixin

from django.contrib.auth.mixins import LoginRequiredMixin

class TaskListView(LoginRequiredMixin, ListView):
    model = Task
    login_url = '/login/'           # where to redirect
    redirect_field_name = 'next'    # parameter for return URL

PermissionRequiredMixin

from django.contrib.auth.mixins import PermissionRequiredMixin

class TaskCreateView(PermissionRequiredMixin, CreateView):
    model = Task
    permission_required = 'tasks.add_task'
    # or multiple permissions:
    permission_required = ['tasks.add_task', 'tasks.view_project']

UserPassesTestMixin

from django.contrib.auth.mixins import UserPassesTestMixin

class TaskEditView(UserPassesTestMixin, UpdateView):
    model = Task

    def test_func(self):
        task = self.get_object()
        return self.request.user == task.owner

Custom Mixin

class OwnerRequiredMixin:
    """Grants access only to the owner of the object."""

    def get_queryset(self):
        qs = super().get_queryset()
        return qs.filter(owner=self.request.user)

class TaskDetailView(LoginRequiredMixin, OwnerRequiredMixin, DetailView):
    model = Task

Inheritance Order (MRO)

# Correct order: mixins BEFORE the base class
class TaskView(LoginRequiredMixin, OwnerRequiredMixin, DetailView):
    ...

# INCORRECT: base class first
class TaskView(DetailView, LoginRequiredMixin):  # LoginRequired won't work
    ...

Python uses C3 linearization โ€” super() calls the next class in the MRO from left to right.

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

๐Ÿ“

Search in Django

You can start with simple Django ORM filters and move to PostgreSQL features when you...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 279
๐Ÿ“

Swagger Documentation with drf-spectacular

drf-spectacular generates an OpenAPI 3.0 schema and Swagger UI for DRF.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 563
๐Ÿ“

settings.py: Django Configuration

settings.py is the central configuration file for a Django project.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 315
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

Django RequestLab: from HTTP to secure production Open course curriculum