Django - 如何在 ajax 函数下显示消息 [英] Django - How to show messages under ajax function
问题描述
我正在使用 AjaxForm 插件提交我的表单而无需刷新.喜欢:
$('#my_form_id').ajaxForm(function(){//关于成功或失败的事情});
这可以正常工作.当我单击提交按钮时,它会在不刷新的情况下保存表单数据.但在此之前;我的模板文件上有 Django 消息,例如:
{% for message in messages %}<div id="notice" align="center">{{ 信息 }}
{% 结束为 %}
这段代码的作用是在帖子保存正确或失败时显示通知.
现在;我不能那样做.我不明白如何在 ajax 函数中使用这些消息标签.
它只是保存帖子.没有通知.
谢谢.
add_post url : url(r'^admin/post/add/$', view='add_post',name='add_post'),
相关观点:
@login_required(login_url='/login/')def add_post(请求):模板名称 = 'add.html'所有者 = request.user如果 request.method == "POST":form = addForm(request.POST)如果 form.is_valid():titleform = form.cleaned_data['title']bodyform = form.cleaned_data['body']checkform = form.cleaned_data['isdraft']n = Post(title=titleform, body=bodyform, isdraft=checkform, owner=owner)n.save()消息.添加消息(请求,消息.成功,'新帖子创建成功!')别的:消息.添加消息(请求,消息.警告,'请填写所有字段!')别的:表单 = addForm()return render_to_response(template_name, {'form': form, 'owner': owner,},context_instance=RequestContext(request))
这些是帮助我解决问题的工具/方法.首先,我有一个名为 render_to_json
的辅助工具方法:
# `data` 是一个 Python 字典def render_to_json(请求,数据):返回 HttpResponse(json.dumps(data, ensure_ascii=False),mimetype=request.is_ajax() 和application/json"或text/html")
我有一个 messages.html
模板来呈现弹出消息所需的 html:
{% for message in messages %}<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>{% 结束为 %}
当创建响应 AJAX 请求的消息时,我使用 Django 的 render_to_string
将消息打包成一个字符串,该字符串存储在 data
字典中,然后使用我的 render_to_json
返回适当的响应:
def my_custom_view(request)# ... 你的视图代码数据 = {'msg': render_to_string('messages.html', {}, RequestContext(request)),}返回render_to_json(请求,数据)
然后,在我的 jQuery $.post(...)
回调函数中,我检查 response
对象是否有 msg
属性,然后将 response.msg
的内容插入到我想要的 DOM 中,如果需要,可以使用 jQuery 转换.我的 base.html
模板包含消息的
容器:
{% 包含 'messages.html' %}
请注意,当您想在实际页面加载(非 AJAX 请求)时显示消息时,上面包含 messages.html
- 如果没有消息,则为空白,但是
仍可用于将 AJAX 接收的消息推送到其中.
最后一部分是我在任何 $.post(...)
回调中用于显示消息的 Javascript 函数(需要 jQuery):
function showPopupMessage(content) {var elMessages = $('#popup-messages-content');如果(elMessages.length && 内容){elMessages.html(内容);}}
I am using AjaxForm plugin to submit my form without refresh. like:
$('#my_form_id').ajaxForm(function(){
//something on success or fail
});
this works correctly. when i click submit button it saves form datas without refresh. But before this ; i had django messages on my template file like:
{% for message in messages %}
<div id="notice" align="center">
{{ message }}
</div>
{% endfor %}
what this code does is displaying notifications if post saved correctly or something failed.
now; i can't do that. i dont understand how i can use these messages tags with ajax functions.
it just saves the post. no notifications.
thank you.
edit :
add_post url : url(r'^admin/post/add/$', view='add_post',name='add_post'),
related view :
@login_required(login_url='/login/')
def add_post(request):
template_name = 'add.html'
owner = request.user
if request.method == "POST":
form = addForm(request.POST)
if form.is_valid():
titleform = form.cleaned_data['title']
bodyform = form.cleaned_data['body']
checkform = form.cleaned_data['isdraft']
n = Post(title=titleform, body=bodyform, isdraft=checkform, owner=owner)
n.save()
messages.add_message(request, messages.SUCCESS,
'New post created successfully!')
else:
messages.add_message(request, messages.WARNING,
'Please fill in all fields!')
else:
form = addForm()
return render_to_response(template_name, {'form': form, 'owner': owner,},
context_instance=RequestContext(request))
These are the tools/methods that helped me to solve the problem. First, I have a helper utility method called render_to_json
:
# `data` is a python dictionary
def render_to_json(request, data):
return HttpResponse(
json.dumps(data, ensure_ascii=False),
mimetype=request.is_ajax() and "application/json" or "text/html"
)
I have a messages.html
template to render the necessary html for the popup message(s):
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
When create a message in response to an AJAX request, I use Django's render_to_string
to package the message(s) into a string that gets stored in a data
dictionary, which then uses my render_to_json
to return an appropriate response:
def my_custom_view(request)
# ... your view code
data = {
'msg': render_to_string('messages.html', {}, RequestContext(request)),
}
return render_to_json(request, data)
Then, in my jQuery $.post(...)
callback function, I check to see if the response
object has a msg
attribute, and then insert the contents of response.msg
into the DOM where I want it needs to be, with jQuery transitions if desired. My base.html
template contains the <ul>
container for the messages:
<ul id="popup-messages-content">
{% include 'messages.html' %}
</ul>
Note that the above includes the messages.html
for the case when you want to display messages on an actual page load (non-AJAX request) - it is blank if there are no messages, but the <ul>
is still available to push AJAX-received messages into.
The last piece is the Javascript function (requires jQuery) I use in any $.post(...)
callbacks to show the messages:
function showPopupMessage(content) {
var elMessages = $('#popup-messages-content');
if (elMessages.length && content) {
elMessages.html(content);
}
}
这篇关于Django - 如何在 ajax 函数下显示消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!