Django User Groups and Permission
We had a content curation application covering 4 roles Admin, Editor, Contributor, and Client.
Each of the roles had certain permission and access rights, and we had to block access to unauthorized roles. This would have been simple if the access had been at model level but we had to give them access at the object level.
For example let us say there were 2 editors editor A and editor B if editor A has created a content X then editor B should not be able to view, edit or delete content X unless he has been assigned to the content X.
Django does provide groups and permissions option but this is a model or table level and not at the object level. Hence we decided on creating groups based on the objects on which we want to provide the access and the users were added to these groups as per requirement or based on the existing state of an object.
So our solution had 3 parts,
- Define the groups
- Add user to respective groups
- Verify access using decorator
We created a constants file where we defined all the groups and permissions, the name of the file was permission_constants.py there was always one file for each application.
The idea here is to create groups for each object on which we want to provide access control.
Below is how we had designed the naming convention of the groups
“Id_of_object_”+”model name”+”string of the group” eg 10_project_super_group where 10 is the id of the project object, project is the name of model and super_group is the name of the group.
Below is the script in utils.py for generating groups and assigning permissions to those groups
Below is the code for calling the above method in signals whenever an object is created. In this case, it’s the project.
The next part is adding a user to the respective groups.
Add user to respective groups
For adding the user to a group we need to retrieve the groups associated with a given user and add our groups to it, refer line number 21 and 22 in the above-mentioned code.
The final step is to enable access control using a decorator.
Verify Access Using Decorator
The main idea behind the steps defined above was to use a single decorator to apply access control for most of the views. Since we had already defined the groups and allocated users to those groups all we had to do was to pass the permissions required to access the view in the decorator and the current user who wants to access the view. If the user was in the group having particular permission then he can access the view or else we sent an error.
Code of the decorator
Code for applying decorator on the views
At BoTree Technologies, we build enterprise applications with our Django team of 20+ engineers.
Consulting is free – let us help you grow!
Choose Your Language
Subscribe to Our Newsletter
- Digital Marketing
- IT Consulting
- Project Management