我正尝试使用基于类的视图,而所有这些最终都显示默认的403 Forbidden页面。.mixin类的顺序正确吗?代码是否会像在get / post中那样被使用,还是会跳过所有内容并发生默认的403重定向?
到目前为止,所有可用的示例都仅指向基于函数的视图中的装饰器@login_required,并使用request对象重定向至登录页面。 documentation提供了一些技巧,但我无法将其与下面的代码一起使用。将错误堆栈也放入。
检查
"GET / HTTP/1.1" 200 2580
Forbidden (Permission denied): /app/custom-view
Traceback (most recent call last):
File "C:\Users\me\.envs\project\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\me\.envs\project\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\me\.envs\project\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\me\.envs\project\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\me\.envs\project\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\me\.envs\project\lib\site-packages\django\contrib\auth\mixins.py", line 108, in dispatch
return self.handle_no_permission()
File "C:\Users\me\.envs\project\lib\site-packages\django\contrib\auth\mixins.py", line 43, in handle_no_permission
raise PermissionDenied(self.get_permission_denied_message())
django.core.exceptions.PermissionDenied
代码:
class UserIsAdminMixin(UserPassesTestMixin):
def test_func(self):
return request.user.groups.filter(name='CustomAdmin').exists()
class CustomAdminView(LoginRequiredMixin, UserIsAdminMixin, TemplateView):
template_name = 'template.html'
# login_url = '/login/'
# redirect_field_name = 'my_link_name'
def get(self, request):
form = CustomForm()
# This does not work neither does setting up login_url
if not request.user.is_authenticated or not request.user.is_staff or not self.request.user.groups.filter(name='CustomAdmin').exists():
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
如果上述方法无效,我愿意尝试this solution
答案 0 :(得分:0)
根据this answer,您可以使用handle_no_permission(self):
处理重定向URL。
简单地:
def handle_no_permission(self):
return redirect('users:create-profile')