如何在通用视图中重定向 [英] How to redirect in a Generic View
问题描述
我正在使用通用视图来呈现我的博客文章:
I am using a generic view to render my blog post item:
class PostUpdateView(UpdateView, LoginRequiredMixin):
model = Post
# etc
我在<$ c上有模型方法$ c> Post Post 模型会导致布尔值 True
或 False
:
@property
def can_edit(self):
return self.displays_set.count() == 0
如果 can_edit
为 False
用于 Post
对象,如何重构视图以将其从我的 UpdateView
重定向到另一个 DetailView
?
If can_edit
is False
for the Post
object, how can I refactor the view to redirect from my UpdateView
to a different DetailView
?
推荐答案
覆盖 dispatch
方法,然后在此处检查 obj.can_edit
。这样,将检查对象的 get
和 post
请求。
Override the dispatch
method, and check obj.can_edit
there. That way the object will be checked for get
and post
requests.
class PostUpdateView(LoginRequiredMixin, UpdateView):
model = Post
def dispatch(self, *args, **kwargs):
obj = self.get_object()
if not obj.can_edit:
return redirect('/readonly-view/')
return super().dispatch(*args, **kwargs)
使用此解决方案, get_object()
被调用两次,因此存在重复的SQL查询。但是,保持代码简单可能是值得的。
With this solution, get_object()
is called twice so there is a duplicate SQL query. However this is probably worth it to keep the code simple.
这篇关于如何在通用视图中重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!