如何使用CBV将PermissionDenied Redirect提升到另一个页面?

时间:2018-08-31 00:19:28

标签: django django-models django-forms django-views

我有一个拥有权限的模型,并且在我的视图中使用CBV(generic.CreateView)或(generic.DetailView),如果登录的用户具有权限,则他可以访问视图,如果不能访问,则可以访问页面禁止显示403。

但是,如果用户没有该视图的权限,则我想引发异常PermissionDenied,并重定向到该错误的特定页面。

我的观点:

class AddJob(LoginRequiredMixin, PermissionRequiredMixin, generic.CreateView)

   permission required = 'can_create_job'
   model = Job
   fields = ['name', 'description', 'salary']
   success_url = reversy_lazy('job_list)
   context_object_name = 'object_name'

有人可以帮助我吗? 谢谢

2 个答案:

答案 0 :(得分:2)

首先,您不能同时执行 重定向 引发404异常

也就是说,如果用户没有权限 ,则可以 重定向到某个页面引发异常。

案例1:提出例外情况
引发异常,您应该在视图类中添加 raise_exception = True

class AddJob(LoginRequiredMixin, PermissionRequiredMixin, generic.CreateView):
    permission_required = 'can_create_job'
    model = Job
    fields = ['name', 'description', 'salary']
    success_url = reversy_lazy('job_list')
    context_object_name = 'object_name'
    raise_exception = True # Change is here

情况2:重定向到特定页面
在您的视图中设置 login_url

class AddJob(LoginRequiredMixin, PermissionRequiredMixin, generic.CreateView):
    permission_required = 'can_create_job'
    model = Job
    fields = ['name', 'description', 'salary']
    success_url = reversy_lazy('job_list')
    context_object_name = 'object_name'
    login_url = '/path/to/specific/page'



如果同时设置login_urlraise_exception会发生什么?

AccessMixin类具有方法handle_no_permission(),该方法将被调用以处理这种情况。

  

Source Code

def handle_no_permission(self):
    if self.raise_exception:
        raise PermissionDenied(self.get_permission_denied_message())
    return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name())

在这里您可以看到,如果您设置 raise_exception = True django将不会考虑login_url < / p>

答案 1 :(得分:1)

您可以做的是添加raise_exception = True来查看课程,这将引发PermissionDenied,即返回带有403(禁止)http状态的响应。参见https://docs.djangoproject.com/en/dev/topics/auth/default/#django.contrib.auth.mixins.AccessMixin.raise_exception

此外,如果您想显示自己的403页面,则可以创建403.html模板,django将在返回403时使用它。请参见https://docs.djangoproject.com/en/dev/ref/views/#the-403-http-forbidden-view

相关问题