在 Django 中 POST 请求后无法执行简单的重定向(使用 HttpResponseRedirect)

bli*_*itz 5 python django

我试图在 Django 中发出 POST 请求后返回 HTTP 响应,但它似乎不起作用。我在下面使用 HttpResponseRedirect 进行了说明。

执行下面的代码时,我看到“hello”消息,但它没有重定向。如果我将“return HttpResponseRedirect('/account/')”行移至底部,那么它会在加载页面时进行重定向,因此该行确实可以正常工作。

if request.POST:
    print('hello')
    return HttpResponseRedirect('/thank-you/')
else:
    return render(request, 'account.html')
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 5

request.method您可以通过将[Django-doc]与您想要的方法进行比较来检查该方法,因此这里request.method == 'POST'. request.POST[Django-doc]是一个QueryDict包含 POST 请求中的参数的文档,但并不是每个 POST 请求都有 POST 参数。如果这样的POST请求没有参数,那么if request.POST将会失败。

因此,您可以使用:

if request.method == 'POST':
    print('hello')
    return HttpResponseRedirect('/thank-you/')
else:
    return render(request, 'account.html')
Run Code Online (Sandbox Code Playgroud)

话虽这么说,您可能想使用redirect(..)[Django-doc]来代替。redirect(..)是一个快捷方式,您可以在其中指定视图的名称。如果您稍后更改视图的路径,那么这仍然有效,因此:

from django.shortcuts import redirect

if request.method == 'POST':
    print('hello')
    return redirect('name-of-view')
else:
    return render(request, 'account.html')
Run Code Online (Sandbox Code Playgroud)

redirect(..)执行“反向查找”并将其生成的路径包装到一个HttpResponseRedirect(..)对象中。所以本质上它是完全相同的,但是这种技术更“稳定”,因为如上所述,如果你改变你的urls.py,反向查找仍然会成功。


Exp*_*tor 3

if request.method == 'POST':
    print('hello')
    return HttpResponseRedirect('/thank-you/')
else:
    return render(request, 'account.html')
Run Code Online (Sandbox Code Playgroud)

那么你需要检查方法

from django.shortcuts import redirect

if request.method == 'POST':
        print('hello')
        return redirect('/thank-you/')
    else:
        return render(request, 'account.html')
Run Code Online (Sandbox Code Playgroud)

感谢 @Willem Van Onsem 指出 POST 需要是一个字符串而不是一个 CONSTANT

  • @Exprator:我认为问题在于您使用“POST”作为标识符,而不是字符串文字。 (2认同)