gpt4 book ai didi

python - '角色'对象没有属性 '__name__'

转载 作者:太空宇宙 更新时间:2023-11-03 13:03:38 25 4
gpt4 key购买 nike

我正在尝试在我的应用程序中实现基于角色的权限。我有一个装饰器 role_required,我可以将一组用户角色传递到其中,只有具有该角色的用户才能访问该 View 。我已经为用户正确分配了角色,但是,现在我收到 AttributeError 声明 'Role' object has no attribute '__name__'

views.py 文件:

m_role_required = method_decorator(role_required)
class AddProposal(FormView):

@m_role_required(roles.space_admin)
def dispatch(self, *args, **kwargs):
return super(AddProposal, self).dispatch(*args, **kwargs)

装饰器role_required:

from django.contrib.auth.decorators import user_passes_test
def role_required(*roles):

def check_role(user):
return getattr(user, 'role', None) in roles
return user_passes_test(check_role)

角色类:

class Roles(object):
_roles_dict = None

@property
def roles_dict(self):

if self._roles_dict is None:
self._roles_dict = {}
for item in self._config:
if isinstance(item, basestring):
# An item like 'manager'
self._roles_dict[item] = None
else:
# Anything else
raise ImproperlyConfigured(_INCORRECT_ARGS)
return self._roles_dict

@property
def choices(self):

return [(role, role) for role in self.roles_dict.keys()]

def __init__(self, config=None):

self._config = config or getattr(settings, 'USER_ROLES', ())

def __getattr__(self, name):

if name in self.roles_dict.keys():
return Role(name=name)
else:
raise AttributeError("No such role exists '%s'" % name)

roles = Roles()

我无法找出引发此错误的原因。谁能帮忙。让我用这个添加追溯,

环境:

Request Method: GET
Request URL: http://127.0.0.1:8000/en-gb/spaces/bithin/proposal/add/


Traceback:

48. class AddProposal(FormView):
File "/home/bithin/gsoc/week3/e-cidadania/src/apps/ecidadania/proposals/views.py" in AddProposal
78. @m_role_required(roles.space_admin)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _dec
34. update_wrapper(_wrapper, func)
File "/usr/lib/python2.7/functools.py" in update_wrapper
33. setattr(wrapper, attr, getattr(wrapped, attr))

Exception Type: AttributeError at /en-gb/spaces/bithin/proposal/add/
Exception Value: 'Role' object has no attribute '__name__'

最佳答案

这可能与 Why do python instances have no __name__ attribute? 重复

简答:类的名称存储在类中,不能直接供实例使用。您可以通过 myinstance.__class__.__name__ 访问实例的类名。

关于python - '角色'对象没有属性 '__name__',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11150501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com