Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django groups, roles and permissions

Tags:

django

I have a question: there's employee app in my project and I want employees to have different titles such as sales representative, manager and etc. and my views behave differently depending on employee's title. For now I have model Titles (title_code, title_name) but I feel like it could've been done with Django's builtin modules. So what do I use for building hierarchy? Groups, roles or permissions?


2 Answers

The django groups, role and permissions system is for allow or denay action in administration pannel, for this reason these three components work together.

  1. If in your application all these type of user have access in admin pannel I suggestion you to use the Groups, roles and permission system
  2. But If your users haven't the access to admin pannel you can avoid using it.

In first option you can create a different roles for every users and allow some permissions for each but if you have groups of users with same permission you can regroup they in a group. For more info view this https://docs.djangoproject.com/en/4.0/topics/auth/default/#permissions-and-authorization

like image 128
Matteo Giuntoni Avatar answered Jan 27 '26 00:01

Matteo Giuntoni


If you do not need any specific privileges for each employee title, then choices would be pretty simple to implement like below

Sample Example

from django.db import models

class Employee(models.Model):
    SALES_MANAGER = 1
    HR_MANAGER = 2
    ENGINEERING_MANAGER = 3
  
    ROLE_CHOICES = (
      (SALES_MANAGER, 'Sales Manager'),
      (HR_MANAGER, 'HR Manager'),
      (ENGINEERING_MANAGER, 'Manager'),
    )
    employee_title = models.CharField(max_length=100, choices=ROLE_CHOICES, default='Manager')

But do note that if you want to add new employee title's then a re-run of migrations would be required. If you need to avoid this then groups would be a better choice.

from django.db import models
from django.contrib.auth.models import Group

class Employee(models.Model):
    employee_title = models.ManyToManyField(Group)

With groups, you would be able to create new entries without any migrations directly from admin panel.

like image 29
Kashyap KN Avatar answered Jan 26 '26 23:01

Kashyap KN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!