0
0
Djangoframework~5 mins

Group-based permissions in Django

Choose your learning style9 modes available
Introduction

Group-based permissions help you manage user access easily by assigning permissions to groups instead of individual users.

You want to give the same access rights to many users at once.
You need to control who can add, change, or delete content in your app.
You want to organize users by roles like 'Editors' or 'Moderators'.
You want to simplify permission management in a growing project.
Syntax
Django
from django.contrib.auth.models import Group, Permission

# Create a group
editors = Group.objects.create(name='Editors')

# Add permissions to the group
permission = Permission.objects.get(codename='change_article')
editors.permissions.add(permission)

# Assign a user to the group
user.groups.add(editors)

Use Group.objects.create(name='GroupName') to make a new group.

Permissions are linked to models and have codenames like add_modelname, change_modelname, or delete_modelname.

Examples
This creates a new group called 'Moderators' to hold permissions.
Django
from django.contrib.auth.models import Group, Permission

# Create a group named 'Moderators'
moderators = Group.objects.create(name='Moderators')
Adds the permission to delete comments to the 'Moderators' group.
Django
permission = Permission.objects.get(codename='delete_comment')
moderators.permissions.add(permission)
Assigns the user to the 'Moderators' group, giving them all its permissions.
Django
user.groups.add(moderators)
Sample Program

This example creates an 'Editors' group, adds the 'change_article' permission, assigns a user 'alice' to this group, and checks if she has the permission.

Django
from django.contrib.auth.models import User, Group, Permission

# Create a group
editors = Group.objects.create(name='Editors')

# Get permission to change articles
change_article_perm = Permission.objects.get(codename='change_article')

# Add permission to group
editors.permissions.add(change_article_perm)

# Create a user
user = User.objects.create_user(username='alice', password='password123')

# Add user to group
user.groups.add(editors)

# Check if user has permission
has_perm = user.has_perm('app_label.change_article')
print(f"User 'alice' has change_article permission: {has_perm}")
OutputSuccess
Important Notes

Always use the full permission name with app label when checking permissions, like app_label.codename.

Groups make it easier to manage many users with the same permissions.

Remember to migrate your database after adding new permissions or models.

Summary

Group-based permissions let you assign permissions to many users at once.

Use groups to organize users by roles and simplify access control.

Check permissions with user.has_perm('app_label.codename').