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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Composing Django's auth mixins lets you express both authentication and fine-grained authorization declaratively.
- 2Overriding get_object once gives every mixin method a consistent, prefetched object to reason about.
- 3test_func turns any boolean check into a per-request permission gate for class-based views.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/team-membership-access-control-in-django-explained-python-1a87/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.