Permissions in Django - groups


Django tip:

Instead of handling permissions for a single user, you can use groups and group-level permissions 👇

from django.contrib.auth.models import Group, User, Permission
from django.contrib.contenttypes.models import ContentType


manager_group, created = Group.objects.get_or_create(name="Library manager")
librarian_group, created = Group.objects.get_or_create(name="Librarian")

content_type = ContentType.objects.get_for_model(Book)
book_permission = Permission.objects.filter(content_type=content_type)

"""
print(post_permission)

<QuerySet [
    <Permission: library | book | Can add book>,
    <Permission: library | book | Can change book>,
    <Permission: library | book | Can delete book>,
    <Permission: library | book | Can view book>
]>
"""

for perm in book_permission:
    if perm.codename == "add_book":
        manager_group.permissions.add(perm)
    else:
        manager_group.permissions.add(perm)
        librarian_group.permissions.add(perm)

user = User.objects.get(username="librarian_jane_doe")
user.groups.add(librarian_group)

"""
print(user.has_perm("store.add_book")) => False
print(user.has_perm("library.delete_book")) => True
print(user.has_perm("library.change_book")) => True
print(user.has_perm("store.view_book")) => True
"""

For more, check out Permissions in Django.