# Contain number of permission list in your system ex can_add_address, can_add_address
class Permissions(models.Model):
permission_name = models.CharField(max_length=255, help_text="permission key")
description = models.CharField(max_length=255, help_text="permission description")
created_by = models.ForeignKey(User, db_index=True)
created_on = models.DateTimeField(auto_now_add=True, help_text="Date when Role is added.")
updated_on = models.DateTimeField(auto_now=True, help_text="Date when Role is modified.")
enabled = models.BooleanField(default=True, help_text="Enable/Disable this object")
# create multiple group
class RoleGroup(models.Model):
name = models.CharField(max_length=255, help_text="Short title of Role")
created_by = models.ForeignKey(User, db_index=True)
created_on = models.DateTimeField(auto_now_add=True, help_text="Date when Role is added.")
updated_on = models.DateTimeField(auto_now=True, help_text="Date when Role is modified.")
enabled = models.BooleanField(default=True, help_text="Enable/Disable this object")
# add group permisson name with RoleGroup ex, HR name group cantaion multiple permissions
class RolePermission(models.Model):
role_group = models.ForeignKey(RoleGroup, related_name='role_permission_group_name')
permission_name = models.CharField(max_length=255, help_text="Short title of permission ex. can_add_address")
# Assign Multiple group to user
class UserGroup(models.Model):
user = models.ForeignKey(User, db_index=True, related_name='role_group')
role_group = models.ForeignKey(RoleGroup, related_name='role_group_name', null = True, blank = True)
created_by = models.ForeignKey(User, db_index=True)
created_on = models.DateTimeField(auto_now_add=True, help_text="Date when Role is added.")
updated_on = models.DateTimeField(auto_now=True, help_text="Date when Role is modified.")
enabled = models.BooleanField(default=True, help_text="Enable/Disable this object")
#create has_permission static method in Util class
class Util :
@staticmethod
def has_permission(user, permission_name) :
role_group = UserGroup.objects.filter(user = user).values_list('role_group_id', flat = True)
permission_names = RolePermission.objects.filter(role_group_id__in = role_group).values_list('permission_name', flat = True)
if permission_name in permission_names:
return True
return False
#Call Permisson Methods
if Util.has_permission(request.user, 'can_edit_address') :
// Not have permisson code
else :
// Have permisson code