Assigning Permissions in Django
Django provides a robust permissions framework that allows you to assign and manage permissions for users and groups. Permissions control access to specific actions or resources within your application.
1. Understanding Permissions
Django automatically creates the following permissions for each model:
add_modelname
: Permission to add an object.change_modelname
: Permission to change an object.delete_modelname
: Permission to delete an object.view_modelname
(Django 2.1+): Permission to view an object.
Custom permissions can also be defined in your model.
2. Assigning Permissions to Users
You can assign permissions to users programmatically or through the Django admin interface.
Example: Assigning Permissions Programmatically
# models.py
from django.contrib.auth.models import User, Permission
from django.contrib.contenttypes.models import ContentType
from .models import MyModel
# Assigning an existing permission to a user
user = User.objects.get(username='john')
permission = Permission.objects.get(codename='change_mymodel')
user.user_permissions.add(permission)
# Verifying the permission
if user.has_perm('app_name.change_mymodel'):
print("User has the permission!")
3. Using Groups for Permissions
Groups in Django allow you to assign a set of permissions to multiple users. This is useful for managing roles.
Creating and Assigning Permissions to a Group
from django.contrib.auth.models import Group, Permission
# Create a group
editors_group = Group.objects.create(name='Editors')
# Assign permissions to the group
permission = Permission.objects.get(codename='change_mymodel')
editors_group.permissions.add(permission)
# Add a user to the group
user = User.objects.get(username='jane')
user.groups.add(editors_group)
# Verifying the permission
if user.has_perm('app_name.change_mymodel'):
print("User has permission via group!")
4. Custom Permissions
Custom permissions can be added to your model using the Meta
class:
# models.py
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
class Meta:
permissions = [
('can_publish', 'Can publish articles'),
]
After defining custom permissions, run python manage.py makemigrations
and python manage.py migrate
to apply them.
Assigning Custom Permissions
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from .models import MyModel
content_type = ContentType.objects.get_for_model(MyModel)
permission = Permission.objects.create(
codename='can_publish',
name='Can publish articles',
content_type=content_type,
)
user = User.objects.get(username='editor')
user.user_permissions.add(permission)
5. Checking Permissions
Permissions can be checked programmatically using the has_perm
method:
if user.has_perm('app_name.change_mymodel'):
print("User has permission to change MyModel.")
6. Restricting Access in Views
Use the permission_required
decorator to restrict access to views based on permissions:
from django.contrib.auth.decorators import permission_required
from django.shortcuts import render
@permission_required('app_name.change_mymodel', raise_exception=True)
def my_view(request):
return render(request, 'my_template.html')
7. Permissions in the Admin Interface
The Django admin interface allows you to assign and manage user and group permissions:
- Go to the Django admin site.
- Select a user or group.
- Check the desired permissions and save the changes.
8. Conclusion
Permissions in Django offer fine-grained control over user actions. Whether through individual user permissions or group-based roles, you can implement a robust access control system in your application.