Django:从单个 URL 返回多个视图而不重定向
使用基于函数的 Django 视图,根据条件在几个不同的视图之间切换很简单,例如:
def base_view(request):
if some_condition():
return foo_view(request)
else:
return bar_view(request)
我找不到一种简单的方法来对新的基于类的通用视图执行相同的操作。我能想到的唯一方法是重新定向,出于各种原因我想避免这样做:
def base_view(request):
if some_condition():
return redirect(reverse("name_of_url_to_class-based_view_foo"))
else:
return redirect("/url_to_class-based_view_bar/")
有什么建议吗?
With function based Django view it was simple to switch between several different views based on a condition, e.g. something like:
def base_view(request):
if some_condition():
return foo_view(request)
else:
return bar_view(request)
I can't find a simple way to do the same with the new class-based generic views. The only way I can think of is to redisrect, which I would like to avoid for various reasons:
def base_view(request):
if some_condition():
return redirect(reverse("name_of_url_to_class-based_view_foo"))
else:
return redirect("/url_to_class-based_view_bar/")
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这相当于您使用基于类的视图的示例。
This is equivalent to your example with class based views.
尽管 Django 文档确实说基于函数的通用视图 现已弃用 我认为切换的唯一原因是您编写的代码较少。
如果您仍打算进行切换,则首先需要确定哪种基于类的视图或混合最合适(单个对象、多个对象、基于日期、表单等)。如果条件用于选择返回不同上下文数据/模板以提供给视图的函数,您可以根据您的用例将条件推送到重写的
get_queryset|get_context_data|get_object|get_template_names
中。例如,
如果所有其他方法都失败并且您仍然确定拥有基于类的视图,您也可以重写 get(self, request, *args, **kwargs) 并在那里进行切换适当的方法。 详细文档正在变得更好,但我仍然发现我自己翻阅源代码来找出如何实现我想要的。
Even though the Django docs do say that the function based generic views are now deprecated I think the only reason to switch would be if you're writing less code.
If you're still set on switching, you'll want to first identify which class based views or mixins are most appropriate (single object, multiple objects, date based, forms, etc.). If the conditional was used to select a function that returns different context data / template to provide to the view, you can push the conditional down into an overridden
get_queryset|get_context_data|get_object|get_template_names
depending on your use case.For example,
If all else fails and you're still determined to have class based views, you could probably also override
get(self, request, *args, **kwargs)
and do the switching there to the appropriate method. The detailed docs are getting better but I've still found myself poking through the source code to figure out how to accomplish what I want.