检查用户是否在Django中具有某些权限

时间:2021-01-07 19:29:22

I have the following class, named custom_class.py. All i need is a way to check in my views if a certain user is admin, and show some DIVs and if not, hide them. Any help appreciated.

我有以下类,名为custom_class.py。我需要的是一种检查我的视图的方法,如果某个用户是管理员,并显示一些DIV,如果没有,隐藏它们。任何帮助赞赏。

class Backend_user:
    parents = {'Administrator': 'None',
               'Supervisor': 'Administrator',
               'Operator': 'Supervisor',
               }
    childs = {'Administrator': 'Supervisor',
              'Supervisor': 'Operator',
              'Operator': 'Boss',
              }

    def __init__(self, user):
        self.user = user
        self.permissions = OrderedDict()
        self.permissions_plural = OrderedDict()
        self.permissions_plural['Administrator'] = 'Administrators'
        self.permissions_plural['Supervisor'] = 'Supervisors'
        if hasattr(user, "administrator"):
            self.my_specialty = getattr(user, 'administrator')
            self.permissions['Administrator'] = True
            self.permissions['Supervisor'] = True
            self.permissions['Operator'] = True
            self.permissions['Boss'] = True
        elif hasattr(user, "supervisor"):
            self.my_specialty = getattr(user, 'supervisor')
            self.permissions['Administrator'] = False
            self.permissions['Supervisor'] = True
            self.permissions['Operator'] = True
            self.permissions['Boss'] = True

1 个解决方案

#1


0  

Assuming that you have a user table with some name which is also a ForeignKey of Backend_user table so you can simply check if user is admin or not. You have to get the user object from your user table then check if it has the attribute or not

假设您的用户表具有某个名称,该用户表也是Backend_user表的ForeignKey,因此您只需检查用户是否为admin。您必须从用户表中获取用户对象,然后检查它是否具有该属性

def some_view(request):
    user_obj = CustomUser.objects.get(id=some_id) # get the user here
    if hasattr(user_obj, "administrator"):  # checking if user is admin
        # show some div
    else:
        # don't show

#1


0  

Assuming that you have a user table with some name which is also a ForeignKey of Backend_user table so you can simply check if user is admin or not. You have to get the user object from your user table then check if it has the attribute or not

假设您的用户表具有某个名称,该用户表也是Backend_user表的ForeignKey,因此您只需检查用户是否为admin。您必须从用户表中获取用户对象,然后检查它是否具有该属性

def some_view(request):
    user_obj = CustomUser.objects.get(id=some_id) # get the user here
    if hasattr(user_obj, "administrator"):  # checking if user is admin
        # show some div
    else:
        # don't show