views:

686

answers:

5

I have a form that redirects to the same page after a user enters information (so that they can continue entering information). If the form submission is successful, I'm returning

HttpResponseRedirect(request.path)

which works fine. However, I'd also like to display some messages to the user in this case (e.g., "Your data has been saved" at the top of the screen). If I weren't redirecting, I'd just return these messages in the context dictionary. With the redirect, however, I can't do this.

So how can I pass template context information when using HttpResponseRedirect?

What I'm trying to do seems like it would be incredibly common, so please excuse me if I'm missing something obvious.

+1  A: 

You can't. HttpResponseRedirect sends a client-side redirect (HTTP status code 302) to the browser, and then the browser re-requests another page.

You can set a URL query string on the redirect, though that will be visible to the user and anyone intercepting HTTP requests (i.e. proxies), and is therefore not suitable for sensitive information.

dcrosta
what about the sessions framework?
skyl
A: 

You add ?saved=1 to the query string and check for it with something like:

saved = request.GET.get('saved', False)
Jeff Ober
+1  A: 

The only way I know of to pass any data with a redirect is to add GET parameters to the URL you're passing in. To avoid XSS hacks you'd want to pass a specific constant like:

[current path you're passing in]?message=saved

And then process the message=saved parameter in the handler for the path you passed in.

A somewhat more complicated way would be not passing the data in the redirect, and instead using something like http://code.google.com/p/django-notify/ to store session-based data that is displayed to the user following the redirect.

Ben
+2  A: 

The best way would probably be to use a coded querystring on the redirect URL... its an old school approach.

You could do something like

/page/?m=1, /page/?m=2, etc

You would then parse that variable with request.GET in the view code and show the appropriate message.

Jasconius
A: 

Some people dont like it because it puts the message with the user rather than the session, but if you are using auth and have a logged in user you can

http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.message_set.create

GET params are so hackable. I think that the most choice way would be to use the sessions framework. That way you can load up whatever you want in the context and get

{{ request.session.foo }}

could be the message or you could

{% ifequal request.session.foo 1 %} Nice work! {% else %} Almost! {% endifequal %}

and other fun stuff.

http://docs.djangoproject.com/en/dev/topics/http/sessions/#using-sessions-in-views

skyl