[Django]-How can I structure Django permissions to have multiple categories of permissions groups?

3👍

I have recently designed such an architecture so the first thing came into my mind would be like this:

  1. Roles: You can override django’s built-in AbstractUser class by adding role-level choices such as:
# models.py
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    """Custom user model with an extra type field"""
    SUPER_USER = 1
    OTHER_ROLE = 2
    SOME_OTHER_ROLE = 3

    USER_TYPE_CHOICES = (
        (SUPER_USER, 'Super user'),
        (OTHER_ROLE, 'Other role'),
        (SOME_OTHER_ROLE, 'Some other role'),
    )

    user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)

# -------------------------------------------------------------------------

# Don't forget to set this User model as your default model
# settings.py
AUTH_USER_MODEL = 'my_app.User'

  1. You can get use of django’s built-in Group model and put a ForeignKey to your Team models and do object-level permission manually.
# models.py
from django.contrib.auth.models import Group
from django.db import models

def Team(models.Model):
    group = models.ForeignKey(Group, on_delete=models.CASCADE)

# -------------------------------------------------------------------------

# You can do object-level permission per group by
# ...
if team.group in permitted_groups:
    # permission granted
    pass
else:
    # permission not granted
    pass
# ...
  1. You can define a Tag model and add as ManyToManyField to your sensitive information model. Similar to the second solution above, you can manually do object-level permission during runtime by relying on your current information’s tags.

Leave a comment