📝 Django

Mixins in Django CBV

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
85
🌳
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

📝

pytest-django: Testing Django

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

📅 30.06.2026 👁️ 138
📝

Django: Template Tags

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

📅 30.06.2026 👁️ 89
📝

Django: Static Files

Static files are CSS, JavaScript, images, and fonts. Django handles them in a specific way:...

📅 30.06.2026 👁️ 79

Did you like the article?

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