Mixins

Compose reusable behavior into views with mixins.

Syntaxclass V(LoginRequiredMixin, CreateView): ...

Mixins are small classes that add behavior to a view through multiple inheritance. A very common one is LoginRequiredMixin, which restricts a view to logged-in users.

List mixins before the base view class so their methods take priority.

Example

Example · python
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import CreateView
from .models import Post

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ["title", "body"]
    login_url = "/login/"

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

When to use it

  • A developer applies LoginRequiredMixin to a CreateView so only authenticated users can access the form.
  • A team creates a custom OwnerRequiredMixin that checks object ownership and returns 403 for others.
  • A developer stacks LoginRequiredMixin and PermissionRequiredMixin to require both login and a specific permission.

More examples

LoginRequiredMixin on a CBV

Combines LoginRequiredMixin with ListView to protect the view and filter to the user's own posts.

Example · python
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView
from .models import Post

class MyPostListView(LoginRequiredMixin, ListView):
    model = Post
    template_name = "blog/my_posts.html"

    def get_queryset(self):
        return Post.objects.filter(author=self.request.user)

PermissionRequiredMixin

Requires the user to have the blog.add_post permission before they can access the create form.

Example · python
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.views.generic.edit import CreateView

class PostCreateView(PermissionRequiredMixin, CreateView):
    model = Post
    fields = ["title", "body"]
    permission_required = "blog.add_post"

Custom ownership mixin

A reusable mixin that raises 403 if the requesting user is not the owner of the object.

Example · python
from django.core.exceptions import PermissionDenied

class OwnerRequiredMixin:
    def get_object(self, queryset=None):
        obj = super().get_object(queryset)
        if obj.author != self.request.user:
            raise PermissionDenied
        return obj

class PostUpdateView(OwnerRequiredMixin, UpdateView):
    model = Post
    fields = ["title", "body"]

Discussion

  • Be the first to comment on this lesson.