Django - 如何在ajax函数下显示消息 [英] Django - How to show messages under ajax function

查看:389
本文介绍了Django - 如何在ajax函数下显示消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AjaxForm插件来提交我的表单而不刷新。像:

I am using AjaxForm plugin to submit my form without refresh. like:

$('#my_form_id').ajaxForm(function(){

        //something on success or fail
    });

这个工作正常。当我点击提交按钮,它保存表单数据而不刷新。但在此之前我在我的模板文件上有django消息,如:

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;我不能这样做我不明白我如何使用这些消息标签与ajax功能。

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.

谢谢。

编辑:

add_post url: url(r'^ admin / post / add / $',view ='add_post',name ='add_post'),

add_post url : url(r'^admin/post/add/$', view='add_post',name='add_post'),

相关视图:

@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))


推荐答案

这些是帮助我解决问题的工具/方法。首先,我有一个帮助程序实用程序方法称为 render_to_json

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"
    )

我有一个 messages.html 模板以显示弹出消息的必要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 %}

当响应AJAX请求创建消息时,我使用Django的 render_to_string 将消息打包成一个字符串,该字符串存储在数据字典中,然后使用我的 render_to_json 返回适当的回复:

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)

然后,在我的jQuery $ .post(...)回调函数,我检查看看响应对象是否有一个 msg 属性,然后将需要的jQuery转换插入到需要的DOM中,将 response.msg 的内容插入。我的 base.html 模板包含消息的< ul> 容器:

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>

请注意,以上内容包括 messages.html 对于在实际页面加载(非AJAX请求)上显示消息的情况下,如果没有消息,则为空白,但< ul> 仍然可以将AJAX收到的消息推送到。

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.

最后一件是Javascript功能(需要jQuery),我在任何 $。 (...)回调以显示消息:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆