我有一些用户可以查看某个 View 。
允许用户登录并使用 403 Forbidden
投诉对于那些看不到该登录信息的用户,我可以使用以下内容(如 here 所述):
@permission_required('polls.can_vote', raise_exception=True)
@login_required
def my_view(request):
...
这确实按预期工作。但我所有的观点都是基于类的观点。从 Django 1.9(终于!)开始,有很多漂亮的 mixin 可以做一些只能通过装饰器才能实现的事情。然而...
class MyClassView(LoginRequiredMixin, PermissionRequiredMixin, TemplateView):
raise_exception = <???>
permission_required = 'polls.can_vote'
template_name = 'poll_vote.html'
这不起作用。因为
raise_exception
标志由 LoginRequiredMixin
使用和 PermissionRequiredMixin
,我无法将其设置为任何内容。raise_exception
是 True
,未登录的用户会收到 403 Forbidden
(我不想要)。 raise_exception
是 False
, 一个用户是 不是 允许查看 View ,将被重定向到登录页面,因为用户已登录,将再次重定向到该页面。创建一个完全不花哨的重定向循环。 当然,我可以实现我自己的 mixin,它的行为符合我的预期,但是在 View 本身中是否有任何 Django 方式来执行此操作? (不在
urls.py
中)
最佳答案
所需的行为是自 2.1 以来的默认行为,因此其他答案已过时:
Changed in 2.1: In older versions, authenticated users who lacked permissions were redirected to the login page (which resulted in a loop) instead of receiving an HTTP 403 Forbidden response. [src]
关于django - PermissionRequiredMixin 和 LoginRequiredMixin 可以结合使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34676751/