'Can't do a simple redirect after POST request in Django (using HttpResponseRedirect)
I am trying to return an HTTP Response after a POST request in Django, it does not seem to be working. I have illustrated that below using HttpResponseRedirect.
When executing below code, I see the 'hello' message but it does not redirect. if I move the 'return HttpResponseRedirect('/account/')' line to the bottom then it does redirect upon loading the page, so the line does work otherwise.
if request.POST:
print('hello')
return HttpResponseRedirect('/thank-you/')
else:
return render(request, 'account.html')
Solution 1:[1]
You inspect the method by comparing request.method [Django-doc] with the method you want, so here request.method == 'POST'. request.POST [Django-doc] is a QueryDict that contains the parameters in the POST request, but not every POST request has POST parameters. If such POST request has no parameters, then if request.POST will fail.
You thus can use:
if request.method == 'POST':
print('hello')
return HttpResponseRedirect('/thank-you/')
else:
return render(request, 'account.html')
That being said, you probably want to use redirect(..) [Django-doc] instead. redirect(..) is a shortcut in which you can specify the name of the view. If you later change the path of a view, then this will still work, so:
from django.shortcuts import redirect
if request.method == 'POST':
print('hello')
return redirect('name-of-view')
else:
return render(request, 'account.html')
The redirect(..) will perform a "reverse lookup" and wrap the path that it generates into a HttpResponseRedirect(..) object. So in essence it is exactly the same, but this technique is more "stable" since as said, if you change your urls.py, the reverse lookup will still succeed.
Solution 2:[2]
if request.method == 'POST':
print('hello')
return HttpResponseRedirect('/thank-you/')
else:
return render(request, 'account.html')
well you need to check the method
from django.shortcuts import redirect
if request.method == 'POST':
print('hello')
return redirect('/thank-you/')
else:
return render(request, 'account.html')
thanks to @Willem Van Onsem for pointing POST needs to be a string and not a CONSTANT
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Willem Van Onsem |
| Solution 2 |
