【问题标题】:Redirect from second view从第二个视图重定向
【发布时间】:2018-08-10 01:27:26
【问题描述】:

这里有一个真正的问题。我在后端有 2 个视图,确实需要从第二个视图重定向

这样的观点:

def first_function(request):
    """ Here is some stuff """
    second_function(request)
    return render(request, 'first.html', context)

def second_function(request)
    """ Check here something """
    if ok:
        return
    else: 
        return redirect('/') # this redirect does not work

【问题讨论】:

    标签: python django http http-headers


    【解决方案1】:

    您的视图second_function 返回响应。只要视图没有引发异常,您的first_function 就会继续,无论该响应的状态代码是什么。

    如果要返回重定向,则必须将结果分配给状态码,然后必须将 second_function 的结果分配给变量,然后检查状态码。

    def first_function(request):
        """ Here is some stuff """
        response = second_function(request)
        if response.status_code == '302':
            return response
        return render(request, 'first.html', context)
    

    这不是构建代码的好方法,但我无法建议替代方案,因为您的代码显示了您真正想要做的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 2017-10-30
      相关资源
      最近更新 更多