django在POST表单提交后显示消息 [英] django display message after POST form submit
问题描述
我有一个带有POST表单的页面,该页面的操作设置为某些url.
即假设此页面网址为/form_url/
:
..
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/
:
..
/submit_url/
中的视图负责处理表单数据.此后,我想返回带有成功消息的表单的同一页面.
在照顾POST表单的视图中,我使用HttpResponseRedirect
以便从浏览器中清除"表单数据.
但是以这种方式,除非执行以下操作,否则我无法在表单页面中显示消息:
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.
我注意到在django管理站点中,对象的删除/添加确实在POST提交后使用重定向,并且仍然以某种方式显示成功消息. 怎么样?
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?
我已经简要地看过django消息传递"应用程序,但是我想先了解它的工作原理.
I've already briefly seen django "messaging" app, but I want to know how it work first..
推荐答案
django管理员使用django.contrib.messages
,您可以像这样使用它:
The django admin uses django.contrib.messages
, you use it like this:
您认为:
from django.contrib import messages
def my_view(request):
...
if form.is_valid():
....
messages.success(request, 'Form submission successful')
在您的模板中:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li {% if message.tags %} class=" {{ message.tags }} " {% endif %}> {{ message }} </li>
{% endfor %}
</ul>
{% endif %}
这篇关于django在POST表单提交后显示消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!