Reputation: 2409
As is clear from this question and the accepted answer, the only way to redirect with a context is to save it in the session. Why doesn't Django have a simple redirect
method that takes a context object like render
does?
For e.g., let us say, I have a login view that accepts both GET
and POST
requests. GET
request simply renders the form in which a user can enter credentials, which will trigger a POST
call to the same view.
def login(request, *args, **kwargs):
if request.method == 'GET':
context = {}
context.update(csrf(request))
return render(request, 'login.html', context=context)
elif request.method == 'POST':
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return redirect('loggedin')
else:
# Redirect with a context object that has 'error':True,
# so that the login template can display error message:
# 'Username/password is incorrect'
redirect('login')
return redirect('invalid')
Please notice that upon the entry of wrong combination of username/password, I would like to redirect the user to the same login page with error variable set in the context so that the template can draw out a warning.
I know, a possible answer would be to invoke render
with custom context than redirect
, but then isn't is a good practice to always use redirect
after a post request?
Thanks.
Upvotes: 1
Views: 936
Reputation: 599630
This is not in any way a limitation of Django, and you don't seem to have thought through how this would even work.
A redirect is a simple HTTP response that tells your browser to go and request another page. How would Django, or any framework, pass a context through that redirect? Where would it go? And the receiving URL would have its own view, which would generate its own context - what would it do with the "redirect" context? How would it know?
But in any case I don't understand why you would want to redirect back to the same page on an error. Simply redisplay it. The redirect-after-POST principle is for successful posts, not unsuccessful ones.
Upvotes: 2