当登录的用户想要更新他尚未创建的帖子(UpdateView)时,test_func函数应将用户重定向到403 Forbidden页面,而不是登录页面。但是,就我而言,即使用户已经登录,它也会重定向到登录页面。有人知道为什么会这样吗?谢谢!
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super(PostUpdateView,self).form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
答案 0 :(得分:1)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
raise_exception = True # <<<---
...
https://docs.djangoproject.com/en/2.1/topics/auth/default/#the-loginrequired-mixin
答案 1 :(得分:0)
您是否尝试过django.core.exceptions中的PermissionDenied?
from django.core.exceptions import PermissionDenied
def edit(request, pk):
if not request.user.is_staff:
raise PermissionDenied
# ...
您可以执行以下操作:
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
raise PermissionDenied