Django version 3.0.5
我想使用PermissionRequiredMixin
在我的视图显示一个横幅信息,就像我对SuccessMessageMixin
所做的那样。
例如,如果一个用户试图删除一个对象,而他们没有权限,permission_denied_message
基本上会被视为一个错误信息和在当前视图中显示为横幅信息。
这可能吗?
的代码,我目前没有工作-它总是重定向到403页。见下文:
class DocDeleteView(PermissionRequiredMixin, SuccessMessageMixin, DeleteView):
model = SlateDoc
success_url = reverse_lazy('slatedoc-list')
success_message = "SlateDoc was deleted!"
permission_required = ('slatedoc.delete_slatedoc')
raise_exception = True
permission_denied_message = "Permission Denied"
def delete(self, request, *args, **kwargs):
if self.has_permission() is False:
messages.error(self.request, self.permission_denied_message)
else:
self.object = self.get_object()
self.object.soft_delete()
messages.success(self.request, self.success_message)
return HttpResponseRedirect(self.get_success_url())
=====================================================================
2021-10-07
所以我已经更新了我的代码一点,现在我可以得到"Permission Denied"错误消息显示,但它仍然重定向到403页。因此,我在403页面的顶部看到了一条红色的错误消息。我还在想怎么让错误信息显示出来
class DocDeleteView(PermissionRequiredMixin, SuccessMessageMixin, DeleteView):
model = SlateDoc
success_url = reverse_lazy('slatedoc-list')
success_message = "SlateDoc was deleted!"
permission_required = ('slatedoc.delete_slatedoc')
raise_exception = False
permission_denied_message = "Permission Denied"
def get_permission_denied_message(self):
self.object = self.get_object()
messages.error(self.request, self.permission_denied_message)
return reverse('slatedoc-detail', kwargs={'pk': self.object.pk})
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
self.object.soft_delete()
messages.success(self.request, self.success_message)
return HttpResponseRedirect(self.get_success_url())
有兴趣的人:这是我用来让它工作的代码。@hendrikschneider是对的-我只需要删除PermissionRequiredMixin
class DocDeleteView(SuccessMessageMixin, DeleteView):
model = SlateDoc
success_url = reverse_lazy('slatedoc-list')
success_message = "SlateDoc was deleted!"
permission_required = ('slatedoc.delete_slatedoc')
permission_denied_message = "Permission Denied"
def delete(self, request, *args, **kwargs):
if not request.user.has_perm(permission_required):
self.object = self.get_object()
messages.error(self.request, self.permission_denied_message)
return redirect(reverse('slatedoc-detail', kwargs={'pk': self.object.pk}))
else:
self.object = self.get_object()
self.object.soft_delete()
messages.success(self.request, self.success_message)
return HttpResponseRedirect(self.get_success_url())