Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django display message after POST form submit

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..

like image 765
user3599803 Avatar asked Feb 25 '15 15:02

user3599803


People also ask

How do I show pop up messages in Django?

To display alert messages in Django, (1) check that the settings are configured properly, (2) add a message to a view function, and (3) display the message in a template. INSTALLED_APPS = [ ... 'django. contrib. messages', ... ]

How do you return a message in Django?

If you leverage the messages framework, you'll still need to add a conditional in the template to display the messages if they exist or not. If I use render() to return a response from a view which is requsted by POST, then if the user refreshes the page the browser will prompt a popup if to send the form again.

How can I write message in Django?

Adding a message To add a message, call: from django. contrib import messages messages. add_message(request, messages.INFO, 'Hello world.

How do you show success message after submitting HTML form?

There are 2 general ways to show a message after submitting an HTML form: Use Javascript AJAX to submit the form and show a message when the processing is complete. Submit the form as usual, and have the server-side script pass back a flag to show the message.


1 Answers

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 %} 
like image 169
damio Avatar answered Sep 25 '22 13:09

damio