Permissions
Authentication tells you who a user is; permissions decide what they're allowed to do. Django includes a flexible permission system so you can let organisers create events, let the events team edit any event and keep everyone else to browsing and RSVPing.
Three built-in flags
| Flag | Meaning |
|---|---|
is_active | The account can log in. Set it to False to disable an account instead of deleting it. |
is_staff | The user may log in to the admin site (but still only sees what their permissions allow). |
is_superuser | The user automatically has every permission. Keep these accounts to a minimum. |
Model permissions
For every model, Django automatically creates four permissions when you run migrate. For Event they are:
| Permission string | Allows |
|---|---|
events.add_event | Creating events |
events.change_event | Editing events |
events.delete_event | Deleting events |
events.view_event | Viewing events (mainly in the admin) |
The format is always "<app_label>.<action>_<modelname>". The admin uses these automatically, and you can check them in your own views.
Groups: permissions for roles
Instead of giving permissions to users one by one, put them in a group that represents a role, such as "Organisers", then add users to the group. You can do this in the admin (Groups, then Add group) or in code:
>>> from django.contrib.auth.models import Group, Permission, User
>>> organisers, created = Group.objects.get_or_create(name="Organisers")
>>> add_event = Permission.objects.get(codename="add_event")
>>> organisers.permissions.add(add_event)
>>> brian = User.objects.create_user("brian", password="test-pass-for-brian-123")
>>> brian.has_perm("events.add_event")
False
>>> brian.groups.add(organisers)
>>> brian.has_perm("events.add_event")
False
>>> brian = User.objects.get(username="brian")
>>> brian.has_perm("events.add_event")
True
Why is the second check still False? Django caches a user's permissions the first time you check them. Fetching the user again from the database gives a fresh object with the new group permission. In normal web requests this isn't a problem, because each request loads the user freshly.
Checking permissions in views
For function views, use the @permission_required decorator. With raise_exception=True, a logged-in user without the permission gets a 403 Forbidden page instead of being sent to the login page again.
events/views.py
from django.contrib.auth.decorators import login_required, permission_required
@login_required
@permission_required("events.add_event", raise_exception=True)
def event_create(request):
... # same body as on the Model Forms page
For class-based views, use PermissionRequiredMixin:
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.views.generic import CreateView
from .forms import EventForm
from .models import Event
class EventCreateView(PermissionRequiredMixin, CreateView):
model = Event
form_class = EventForm
permission_required = "events.add_event"
def form_valid(self, form):
form.instance.organiser = self.request.user
return super().form_valid(form)
Inside any view you can also check directly: if request.user.has_perm("events.delete_event"):.
Checking permissions in templates
Templates get a perms variable. Hide buttons that a user can't use:
{% if perms.events.add_event %}
<a href="{% url 'events:event_create' %}">+ New event</a>
{% endif %}
Only hiding the button in the template. Anyone can type /events/new/ into the address bar. The template check is for a tidy interface; the real protection must be in the view, with a decorator, mixin or has_perm() check.
Object-level rules: "only the organiser can edit"
Model permissions are all-or-nothing: change_event means "can change any event". Often you want rules about a specific object, such as "organisers may edit only their own events, but the events team may edit all of them". UserPassesTestMixin handles this nicely:
events/views.py
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import UpdateView
from .forms import EventForm
from .models import Event
class EventUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Event
form_class = EventForm
def test_func(self):
event = self.get_object()
user = self.request.user
return event.organiser == user or user.has_perm("events.change_event")
If test_func() returns False for a logged-in user, they get a 403 page. In a function view, the same idea looks like this:
from django.core.exceptions import PermissionDenied
if event.organiser != request.user and not request.user.has_perm("events.change_event"):
raise PermissionDenied
Custom permissions
You can add permissions of your own in a model's Meta, for example to control who may feature an event on the home page:
events/models.py
class Event(models.Model):
# ... fields ...
class Meta:
ordering = ["starts_at"]
permissions = [
("feature_event", "Can feature events on the home page"),
]
After makemigrations and migrate, the permission events.feature_event appears in the admin and works with has_perm(), decorators and perms in templates just like the built-in ones.
Design your roles first, on paper: who are your users (students, organisers, events team), and what can each do? Then create one group per role. It's much easier to manage than giving out permissions one at a time.
Key points
is_staffallows admin login;is_superusergrants every permission.- Django creates
add,change,deleteandviewpermissions for every model. - Give permissions to groups that represent roles, then add users to groups.
- Enforce permissions in views with
@permission_required,PermissionRequiredMixinorUserPassesTestMixin; usepermsin templates only to tidy the interface.
Tip: use the ← and → keys to move between pages.
