django display message after POST form submit

user3599803 picture user3599803 · Feb 25, 2015 · Viewed 45.6k times · Source

I have a page with a POST form, that have a action set to some url.
i.e assume this page url is /form_url/ : ..

The view in /submit_url/ take care of the form data. After this, I want to return the same page of the form with a success message. In the view that take care for the POST form, I use HttpResponseRedirect, in order to "clear" the form data from the browser. But in this way I can't display a message in the form page, unless I do something like:

return HttpResponseRedirect("/form_url/?success=1")

and then check for this parameter in the template. I don't like this way, since if the user refreshes the page, he will still see the success message.

I've noticed that in django admin site, the delete/add of objects does use redirect after POST submit, and still display a success message somehow. How?

I've already briefly seen django "messaging" app, but I want to know how it work first..

Answer

damio picture damio · Aug 11, 2016

The django admin uses django.contrib.messages, you use it like this:

In your view:

from django.contrib import messages

def my_view(request):
    ...
       if form.is_valid():
          ....
          messages.success(request, 'Form submission successful')

And in your templates:

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