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..
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', ... ]
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.
Adding a message To add a message, call: from django. contrib import messages messages. add_message(request, messages.INFO, 'Hello world.
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.
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With