Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass template context information when using HttpResponseRedirect in Django?

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.

like image 500
Jeff Avatar asked Sep 23 '09 01:09

Jeff


4 Answers

For the sake of completion and future reference, you can now use the messages framework. After you install it:

views.py

from django.contrib import messages

def view(request):
  # your code
  messages.success(request, "Your data has been saved!")
  HttpResponseRedirect(request.path)

template.html

{% if messages %}
<ul class="messages">
  {% for message in messages %}
  <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
  {% endfor %}
</ul>
{% endif %}
like image 101
João Pesce Avatar answered Nov 17 '22 18:11

João Pesce


if you are using auth and have a logged in user you could:

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

GET params are also hackable. The querystring, as mentioned in other answers, could be used.

I think the most preferred 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 }} 

foo could be the message or you could do:

{% 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

like image 45
Skylar Saveland Avatar answered Nov 17 '22 16:11

Skylar Saveland


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.

like image 8
dcrosta Avatar answered Nov 17 '22 18:11

dcrosta


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.

like image 7
M. Ryan Avatar answered Nov 17 '22 16:11

M. Ryan