【发布时间】:2020-06-05 07:06:03
【问题描述】:
你好我想知道我们是否可以让一个页面只能由管理员(超级用户)访问我在文档中找不到任何东西,但我希望我的分析页面只能由超级用户访问,而无需在配置文件中使用布尔值
【问题讨论】:
标签: django
你好我想知道我们是否可以让一个页面只能由管理员(超级用户)访问我在文档中找不到任何东西,但我希望我的分析页面只能由超级用户访问,而无需在配置文件中使用布尔值
【问题讨论】:
标签: django
您可以使用@staff_member_required decorator [Django-doc] 来装饰视图,例如:
# app/views.py
from django.contrib.admin.views.decorators import staff_member_required
@staff_member_required
def my_view(request):
# …
或者对于基于类的视图 (CBV),您可以使用 UserPassesTestMixin mixin [Django-doc]:
# app/views.py
from django.contrib.auth.mixins import UserPassesTestMixin
class StaffMemberRequiredMixin(UserPassesTestMixin):
def test_func(self):
return self.request.user.is_staff
class MyView(StaffMemberRequiredMixin, View):
# …
【讨论】:
{% if request.user.is_superuser %}
so your html tags and other data you want to show
{% else %}
you're not authorized to see the content
{% end %}
或者你也可以在views.py中做这样的限制:
def view_p(request):
if not request.user.is_superuser:
return HttpResponseBadRequest()
如果你想经常做这个限制,创建一个装饰器或使用现有的装饰器会更好, 另一个好主意是代替 Http-bad-request,向用户发送一条更好的消息,以解释认为他/她的请求不好的原因。(可能会返回包含该消息的 html 页面) 还看到这个: Django: Hide button in template, if user is not super-user
【讨论】: