python - 返回重定向 View

标签 python django

我需要返回RedirectView。这些都不起作用:

class FooView(View):
  return SomeRedirectView

class FooView(View):
  return SomeRedirectView.as_view()

class FooView(View):
  return HTTPResponseRedirect(SomeRedirectView)

如何返回 RedirectView?

编辑:伙计们,我的想法是我需要从类里面回来。但似乎没有人这样做。那么如何从一个类返回呢?

编辑2:抱歉,我还不够清楚。我知道如何使用单个 RedirectView 来重定向用户。我有一个重定向 View :

class MyRedirectView(RedirectView):
  def get_redirect_url():
    return 'www.google.com'

我需要将 MyRedirectView 作为单独的 View ,因为它在某处用作独立 View 。但后来我有了完全不同的 View ,它必须使用逻辑,然后“调用”MyRedirectView

问题是,SomeOtherView 必须是什么样子? (不是 MyRedirectView)

class SomeOtherView(View):
  def get():
    return MyRedirectView ????

解决方案:在其他 SO 成员的帮助下,我得出的结论是我的想法是错误的。我不必重复代码,我可以使用函数。我无法调用类或返回 View 。但我可以使用公共(public)函数并从 MyRedirectView 和 FooView (或任何其他 View )内部调用它。

感谢大家的帮助和良好的讨论!

最佳答案

我不知道你为什么认为你需要返回一个 View 。如果您现有的 View 需要返回重定向,那么您应该简单地这样做:

from django.shortcuts import redirect


class SomeOtherView(View):
  def get(request):
    ... logic here...
    return redirect(my_redirect_destination)

关于python - 返回重定向 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25085349/

相关文章:

django - 我可以在同一个应用程序中使用不同的根 URL 吗?

python - 如何在python中获取文件关闭事件

python - Li-Fi通信中的编码/解码问题

python - 无法访问 Django 模板中的 UserProfile 模型字段。试过 {{ user.userprofile }}

python - django 插入或更新记录

python - inAttributeError : module 'reportlab.pdfgen.canvas' has no attribute 'acroform'

python - 将带有逗号空格逗号的 CSV 转换为浮点型

python - 多个字典放入列表中

python - 在哪里可以找到函数的 kwargs/args 文档

django - 当我在 Django 站点中切换语言时没有显示翻译的字符串