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


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.

9/23/2009 1:19:17 AM

Accepted Answer

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.

9/23/2009 1:27:14 AM

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

from django.contrib import messages

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


{% if messages %}
<ul class="messages">
  {% for message in messages %}
  <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
  {% endfor %}
{% endif %}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow