Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 77 ยท Authentication and Security

Permissions, Groups and Authorization

Control who can do what in Django: model permissions, has_perm(), groups, PermissionRequiredMixin, UserPassesTestMixin and patterns for object-level access.

Knowing who a user is (authentication) is only half of access control. The other half, authorization, decides what that user may do: edit this article, publish that one, see the finance report. Django has a permission system built into django.contrib.auth that works for the admin and for your own views alike.

You will learn how Django creates permissions for every model, how to check them with has_perm(), how groups bundle permissions for roles, how to protect class-based and function-based views, and why per-object rules ("only the author can edit") need a pattern of their own. All examples run live in your browser on a small blog app.

The permission model

For every model Django creates four permissions when you run migrate: add, change, delete and view. Each is a row in the Permission table and has a code name like change_post. In code you refer to it as "<app_label>.<codename>", for example "blog.change_post".

You can add your own in the model's Meta. A custom permission is just a name that you then check in views; Django attaches no behavior to it.

Python
class Post(models.Model):
    ...
    class Meta:
        permissions = [("publish_post", "Can publish posts")]

Permissions reach a user in two ways: directly through user_permissions, or through the groups the user belongs to. A superuser passes every check without needing any permission, and an inactive user passes none.

flowchart LR
    U["User"] -->|"user_permissions"| P["Permission<br/>blog.change_post"]
    U -->|"groups"| G["Group<br/>Editors"]
    G -->|"permissions"| P
    P --> C{"user.has_perm(...)"}
    S["is_superuser"] -->|"always True"| C

A permission check combines a user's own permissions, their groups' permissions and the superuser flag.

Checking permissions and using groups

user.has_perm("blog.change_post") returns a boolean. has_perms([...]) requires all of them, get_all_permissions() returns the full set, and get_group_permissions() only those that come through groups. Templates can use perms.blog.change_post.

Permissions are cached on the user object the first time you ask. If you change a user's permissions in the same request and then check again, you will see the old answer until you fetch the user afresh. The demo below shows this on purpose.

Groups are named bundles of permissions. Create roles such as "Editors" and "Moderators", give each group its permissions once, and put users into groups. When a role changes, you edit one group instead of every user.

Python Permissions and groups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Four permissions appear for Post without you creating any, and the custom publish_post is there too. The second check on ada still says False because the first call cached the answer on that object; a fresh query gives the true result. In a real web request that is rarely a problem because the user is loaded once per request.

Protecting views

For class-based views use mixins; put them to the left of the view class so their checks run first:

  • LoginRequiredMixin requires a logged-in user.
  • PermissionRequiredMixin requires permission_required (a string or list of strings).
  • UserPassesTestMixin calls your test_func() and requires it to return True.

For function-based views use the decorators @login_required, @permission_required("blog.publish_post") and @user_passes_test(function).

What happens on failure depends on raise_exception. By default an anonymous visitor is redirected to the login page, while a logged-in user without the permission gets a 403 Forbidden response (it would be pointless to send them to a login page again). Set raise_exception = True and everyone who fails gets a 403 instead, which suits APIs.

Requiring a group in a class-based view

PermissionRequiredMixin checks permissions; sometimes the rule is simply "members of the Managers group". Django has no built-in mixin for that, but all the access mixins share a base class, AccessMixin, which gives you handle_no_permission(). It already implements the behaviour from the previous section: anonymous visitors are redirected to the login page, and logged-in users get PermissionDenied (403). A small group mixin is therefore only a few lines.

Python A GroupRequiredMixin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The anonymous visitor was redirected to /login/?next=/reports/, the user without a group got a 403, and the superuser passed without belonging to any group. Because group_required is a plain class attribute, each view declares its own list of allowed groups. For a function-based view, @user_passes_test(lambda u: u.groups.filter(name="Managers").exists()) does the same job.

Prefer permissions over group names when you can: a check for blog.publish_post keeps working if you rename the group or add a second group that may publish. Group-name checks are fine for coarse "role" gates in small projects.

Object-level rules

Model permissions are all-or-nothing for a table: change_post means "may change any post". Most real sites also need "an author may change their own posts". Django's default backend does not do per-object checks, so you write them yourself with two simple patterns:

  1. Filter the queryset. In list and detail views, start from Post.objects.filter(owner=request.user). Rows the user does not own simply do not exist for them, so they get a 404.
  2. Check in test_func() (or at the top of a function view) by comparing the object's owner with request.user, optionally allowing users with a broader model permission as well.

For complex needs such as sharing a single document with a single colleague, third-party packages like django-guardian or django-rules add per-object permissions on top of the same API. They are not part of this site's runner, so this lesson sticks to the built-in tools.

Python Permission mixins and ownership checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Compare the two publish views. With the default settings the anonymous visitor is sent to the login page (a 302 with ?next=), while the logged-in ada gets a 403. With raise_exception = True both get a 403. UserPassesTestMixin is flexible: here it lets the owner and anyone holding blog.change_post in, and the get_object_or_404 call turns a missing post into a 404 before any permission question arises.

Hiding a button in a template is not security. Always enforce permissions in the view (or the API) too, because anyone can send a request without ever seeing your buttons. Use template checks only to make the interface tidier.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you refer to the 'change' permission of a model Post in the app 'blog'?

    Permissions are written as '<app_label>.<codename>' and the default codenames are add_, change_, delete_ and view_ followed by the lower-case model name.
  2. 2. What does has_perm() return for an active superuser?

    Active superusers pass every permission check. Inactive users fail every check, even superusers.
  3. 3. A logged-in user without the required permission visits a view using PermissionRequiredMixin with default settings. What do they get?

    Anonymous users are redirected to login, but authenticated users who lack the permission get 403 because logging in again would not help. raise_exception=True makes anonymous users get 403 too.
  4. 4. Which approach lets authors edit only their own posts with Django's built-in tools?

    change_post applies to every row. Per-object rules need an explicit check against the object, either by filtering the queryset or inside UserPassesTestMixin.test_func().
  5. 5. Why might has_perm() return a stale answer right after you add a permission to the same user object?

    The backend caches permissions on the user object. Re-fetch the user (or delete the cached attributes) to see changes.

Summary

  • Django creates add, change, delete and view permissions for each model; add your own in Meta.permissions.
  • Check with user.has_perm("app.codename"); superusers pass everything and inactive users nothing.
  • Groups bundle permissions into roles; users get permissions directly or through groups.
  • Protect views with LoginRequiredMixin, PermissionRequiredMixin and UserPassesTestMixin (or the matching decorators).
  • Anonymous failures redirect to login; logged-in failures get 403; raise_exception = True always gives 403.
  • Per-object rules are your job: filter by owner or check in test_func(). Never rely on hidden buttons.

Next up: Sessions and Cookies.