Django——要求页面有一定的访问级别
Django -- Requiring a certain access level for pages
在我的 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', {})
试试这个..
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):
[...]
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', {})
在我的 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', {})
试试这个..
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):
[...]
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', {})