python 39 lines · 7 steps

Team membership access control in Django

A reusable mixin that gates a DetailView so only active members of the object's team can view it.

Explained by highlit
1from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
2from django.shortcuts import get_object_or_404
3from django.views.generic import DetailView
4 
5from .models import Project
6 
7 
8class TeamMemberRequiredMixin(LoginRequiredMixin, UserPassesTestMixin):
9 team_url_kwarg = "team_slug"
10 raise_exception = True
11 permission_denied_message = "You must be a member of this team."
12 
13 def get_team(self):
14 obj = self.get_object()
15 return getattr(obj, "team", obj)
16 
17 def test_func(self):
18 team = self.get_team()
19 return team.memberships.filter(
20 user=self.request.user,
21 is_active=True,
22 ).exists()
23 
24 
25class ProjectDetailView(TeamMemberRequiredMixin, DetailView):
26 model = Project
27 context_object_name = "project"
28 template_name = "projects/detail.html"
29 
30 def get_object(self, queryset=None):
31 return get_object_or_404(
32 Project.objects.select_related("team"),
33 slug=self.kwargs["slug"],
34 )
35 
36 def get_context_data(self, **kwargs):
37 context = super().get_context_data(**kwargs)
38 context["members"] = self.get_team().memberships.select_related("user")
39 return context
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Composing Django's auth mixins lets you express both authentication and fine-grained authorization declaratively.
  2. 2Overriding get_object once gives every mixin method a consistent, prefetched object to reason about.
  3. 3test_func turns any boolean check into a per-request permission gate for class-based views.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Team membership access control in Django — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code