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
import random import click from faker import Faker
Building a Flask seed command with Click
cli
database seeding
orm
Intermediate
7 steps
python
import smtplib from email.message import EmailMessage from threading import Thread
Sending welcome emails off the request thread in Flask
background-threads
app-context
email
Intermediate
8 steps
python
import uuid from pathlib import Path from fastapi import APIRouter, File, Form, HTTPException, UploadFile
Handling multipart file uploads in FastAPI
file-upload
validation
multipart-form
Intermediate
6 steps
python
from copy import deepcopy from typing import Any, Mapping
How a recursive deep merge works in Python
recursion
immutability
dictionaries
Intermediate
6 steps
python
from difflib import SequenceMatcher from bisect import bisect_left, bisect_right
Building a fuzzy autocomplete matcher
fuzzy-matching
binary-search
ranking
Intermediate
9 steps
python
import secrets from datetime import datetime, timedelta, timezone from fastapi import APIRouter, Cookie, Depends, HTTPException, Response, status
Cookie session auth in FastAPI
session-authentication
cookies
dependency-injection
Intermediate
8 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.