How to Work Group Level Permissions in Django?

Published On: 01/11/2022 | Category: Django


Hi Dev,

Today our leading topic is how to work group-level permissions in django. it's simple example of django group-level permissions example. I explained simply about how to use permission in django. you can see group permissions in django. Let's get started with group-level permissions in django example.

Describe the operation of Django's groups and permissions. Utilize Django's built-in group permission system to its full potential.

Here i explained simply step by step example of django group permissions example.

Group-level Permissions

It takes time and is not scalable to have to give people rights every time. There may be times when you want to give a group of users additional permissions. Django groups come into play in this situation.

What's group?: Group models are a general method of classifying users so that you may assign them labels or rights. A user may be a part of countless groups.

When creating a user, you may simply assign the user to a group, and as a result, the person will have all the permissions from that group. Django allows you to build groups to categorise users and provide permissions to each group.

To create a group, you need the Group model from django.contrib.auth.models.

Let's create groups for the following roles:

  • Author: Can view and add posts
  • Editor: Can view, add, and edit posts
  • Publisher: Can view, add, edit, and delete posts
from django.contrib.auth.models import Group, User, Permission
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404

from blog.models import Post

author_group, created = Group.objects.get_or_create(name="Author")
editor_group, created = Group.objects.get_or_create(name="Editor")
publisher_group, created = Group.objects.get_or_create(name="Publisher")

content_type = ContentType.objects.get_for_model(Post)
post_permission = Permission.objects.filter(content_type=content_type)
print([perm.codename for perm in post_permission])
# => ['add_post', 'change_post', 'delete_post', 'view_post']

for perm in post_permission:
    if perm.codename == "delete_post":
        publisher_group.permissions.add(perm)

    elif perm.codename == "change_post":
        editor_group.permissions.add(perm)
        publisher_group.permissions.add(perm)
    else:
        author_group.permissions.add(perm)
        editor_group.permissions.add(perm)
        publisher_group.permissions.add(perm)

user = User.objects.get(username="test")
user.groups.add(author_group)  # Add the user to the Author group

user = get_object_or_404(User, pk=user.id)

print(user.has_perm("blog.delete_post")) # => False
print(user.has_perm("blog.change_post")) # => False
print(user.has_perm("blog.view_post")) # => True
print(user.has_perm("blog.add_post")) # => True

I hope it will help you....

Happy Coding!