← Back to Django, page 5

django-0083 · Medium mid

How do Django permissions and groups work, and what are the common pitfalls such as permission caching and superusers?

Every model gets add, change, delete and view permissions stored in the auth_permission table. Users get them directly or through groups, and user.has_perm("app.change_student") checks them. Superusers pass every check, inactive users pass none, and permissions are cached on the user object after the first check, so a changed permission is not seen until the user is re-fetched. Object-level permissions need an extra backend or your own rules.

Full answer

Model-level permissions:

  • makemigrations/migrate creates four permissions per model (add_, change_, delete_, view_) with codename like change_student and content type pointing at the model. Custom ones go in Meta.permissions = [("approve_result", "Can approve result")].
  • Check with user.has_perm("school.approve_result") (format app_label.codename), user.has_perms([...]), and in views with PermissionRequiredMixin, @permission_required, or in DRF with DjangoModelPermissions.
  • Assign directly with user.user_permissions.add(perm) or via a Group: group.permissions.add(perm), user.groups.add(group). Groups represent roles ("Teachers", "Registrars"), which is easier to manage than per-user permissions.
  • Rules: is_superuser=True returns True for everything; is_active=False returns False for everything (even for superusers); staff status only grants admin access, not permissions.

Caching pitfall: ModelBackend caches the permission set in user._perm_cache (and _user_perm_cache, _group_perm_cache) the first time you call has_perm. If you add a permission and check again on the same object, the answer is stale. Re-fetch the user (User.objects.get(pk=...)), which every new request does anyway, or delete the cache attributes in tests. This surprises people in tests and in long-running scripts.

Other points:

  • Permissions are created after migrations by the post_migrate signal. Data migrations that reference permissions must run after those exist or create them explicitly.
  • Do not hard-code permission primary keys; look up by content_type and codename.
  • has_perm triggers queries (cached afterwards); in templates, perms.school.change_student uses the same cache.
  • Object-level permissions (can this teacher edit this class?) are not built in. Use a package such as django-guardian, or implement has_object_permission in DRF or check ownership in get_queryset().
  • Prefer permission checks over is_staff or role-name string comparisons in code, and test with real groups.
  • Admin respects model permissions for each action, which is how read-only staff roles are built.
python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.contrib.auth.models import Group, Permission, User
from django.core.management import call_command

call_command("migrate", verbosity=0)       # creates auth tables and the default permissions

asha = User.objects.create_user("asha", password="pw-123456")
perm = Permission.objects.get(content_type__app_label="auth", codename="change_group")
print("direct perm:", asha.has_perm("auth.change_group"))

asha.user_permissions.add(perm)
print("same object after add (stale cache):", asha.has_perm("auth.change_group"))   # the cache was filled by the first call
asha = User.objects.get(pk=asha.pk)
print("re-fetched user:", asha.has_perm("auth.change_group"))

teachers = Group.objects.create(name="Teachers")
teachers.permissions.add(Permission.objects.get(content_type__app_label="auth", codename="view_group"))
ravi = User.objects.create_user("ravi", password="pw-123456")
ravi.groups.add(teachers)
ravi = User.objects.get(pk=ravi.pk)
print("via group:", ravi.has_perm("auth.view_group"), "| not granted:", ravi.has_perm("auth.delete_group"))

root = User.objects.create_superuser("root", password="pw-123456")
print("superuser:", root.has_perm("auth.delete_group"))
root.is_active = False
print("inactive superuser:", root.has_perm("auth.delete_group"))
print("codenames for auth.group:", sorted(Permission.objects.filter(content_type__model="group").values_list("codename", flat=True)))

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. It runs migrate on an in-memory SQLite database to create the auth tables and default permissions. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): direct perm: False same object after add (stale cache): False re-fetched user: True via group: True | not granted: False superuser: True inactive superuser: False codenames for auth.group: ['add_group', 'change_group', 'delete_group', 'view_group']

Key points

  • Four default permissions per model; custom ones in Meta.permissions
  • Users get permissions directly or via groups; prefer groups
  • Superuser passes everything; inactive user passes nothing
  • has_perm caches on the user object, so re-fetch after changes
  • Object-level permissions need extra logic or a package

Common mistakes

  • Hard-coding permission primary keys
  • Expecting has_perm to see a change on a user object that already checked
  • Using is_staff as an authorization check
  • Forgetting that an inactive user fails every check, even a superuser
  • Granting permissions per user instead of through groups

Follow-ups

  • How would you implement object-level permissions?
  • How do DRF permission classes use these permissions?
  • How do you create groups and permissions in a data migration?

Tips

  • Recite the four default codenames
  • Mention the cache pitfall
  • Say groups over per-user grants