在我的Django项目中,我想限制一个页面,具体取决于他们是否具有100,200等的访问级别。我尝试为此创建一个包装器,如login_required
,但我不知道如何访问用户模型。有什么建议吗?
示例:
def required_access(access):
if access <= user.access:
print 'The user can access this page, their access level is greater than or equal to whats required.'
else:
print 'This page cannot be viewed, their access level is too low.'
@login_required
@required_access(300)
def foo(request):
return render(request, 'bar.html', {})
答案 0 :(得分:1)
Python装饰器可以访问包装函数参数。
有了这些知识,我们可以改变我们的装饰器,以便访问request.user对象。这假设my_view()
的第一个参数将始终是请求对象。
def required_access(access=None):
def wrap(func):
def inner(*args, **kwargs):
if access <= args[0].user.access:
print 'The user can access this page, their access level is greater than or equal to whats required.'
else:
print 'This page cannot be viewed, their access level is too low.'
return func(*args, **kwargs)
return inner
return wrap
@login_required
@required_access(access=300)
def foo(request):
return render(request, 'bar.html', {})
答案 1 :(得分:0)
试试这个..
from django.contrib.auth.decorators import user_passes_test
def email_check(user):
return user.email.endswith('@example.com')
@user_passes_test(email_check)
def my_view(request):
[...]