Managing user access and permissions is crucial to ensure users can only perform authorized actions. Django provides a flexible system for managing user permissions and groups, enabling role-based access control (RBAC) efficiently.
Understanding Permissions in Django
Django's built-in permissions system works at the model level. By default, each model in Django has three permissions:
- add: Permission to add a new record.
- change: Permission to change an existing record.
- delete: Permission to delete a record.
These permissions are created automatically when running makemigrations and migrate.
Defining Custom Permissions
Consider a project having an app named 'users'. Custom permissions can be defined in the model's Meta class.
In users/models.py:
Migrate the Database
Run the following command for migrations:
python manage.py makemigrations users
python manage.py migrate
Creating Groups and Assigning Permissions
Option A: Using Django Admin Panel
- Login to Django admin.
- Click on Groups.
- Create groups like level0, level1, level2.
- Assign relevant permissions to each group.
Programmatically Creating Groups and Assigning Permissions
Open Django shell:
python manage.py shell
- Groups represent user levels (e.g., Starter, Golden, Diamond).
- Permissions are linked to the User model via ContentType.
- user.groups.add(group) grants the user all permissions assigned to the group.
Assigning Users to Groups
Users can be added to groups through the Admin Panel or programmatically:
- Fetch a user and a group.
- Use user.groups.add() to assign the user to the group.
- The user automatically inherits all permissions associated with that group.
Restricting Access Based on Permissions in Views
1. Function-Based Views (FBVs)
Use Django's user_passes_test decorator or a custom group-based decorator:
- user_passes_test runs the in_groups function to verify group membership.
- If the user is not authenticated or not in the allowed groups, access is denied..
- Ensures only authorized groups can access specific views.
2. For Class-Based Views
Use a mixin to add reusable functionality that enforces group membership for accessing the view:
Example usage: