在Ajax请求后返回Django模型进行模板渲染 [英] Return Django Models for Template Rendering after an Ajax Request

查看:322
本文介绍了在Ajax请求后返回Django模型进行模板渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的网页创建基于AJAX的搜索.到目前为止,我已经能够发送表单数据,并对我的Django模型进行适当的调用.我很难过的是只是将Queryset发回并使用Django模板系统进行渲染.非常感谢您的帮助/建议.

I would like to create an AJAX-based search for my webpage. So far I am able to send the form data and make the appropriate call to my Django model. What I am having a hard time with is just sending the Queryset back and having it rendered using the Django templating system. Your help/advice is greatly appreciated.

这是我正在使用的代码.

Here is the code I am working with.

views.py

if request.is_ajax():
    if request.method == 'POST':
        format = 'json'
        mimetype = 'application/json'
        try:
            q = request.POST['obj']
            o = Object.objects.filter(name__icontains=q)
            return render_to_response( 'project_view_objects.html', {'username': request.user.username, 'results':o})

view.html

view.html

<script>
    $(document).ready(function(){

    $("#search_form").submit(function(event)
    {
        event.preventDefault();


        $.ajax({
            type: "POST",
            url: "/objects/search/",
            data: $(this).serialize(),
            processData: false,
            dataType: "json"
            });
    });});
</script>

<article>
    <blockquote>
        <form class="create_form" id="search_form">
            <p>
                <input id="objectSearchNameInput" type="text" name="obj" value="Object name">
                <input type="submit" value="search objects">
            </p>
        </form>
    </blockquote>
</article>
<br />

{% if results %}
<blockquote>
    <aside class="column">
        {% for object in results %}
            <b><a href="#" class="extra-text-special">{{ object.name }}</a></b><br />
        {% endfor %}
    </aside>
    <aside class="column">
        {% for object in results %}
            <font class="extra-text-nospecial">{{ object.created_when }}</font><br />
        {% endfor %}
    </aside>
</blockquote>
{% else %}
    <p>haha</p>
{% endif %}

此刻,我在页面上看到的全部是哈哈".

At the moment, all I see displayed on the page is 'haha'.

推荐答案

您所缺少的是,在触发AJAX时,模板已经被渲染-当然必须如此,因为模板是服务器-一侧,而javascript是客户端.

The thing you're missing is that the template has already been rendered by the time the AJAX is fired - as of course it must be, because templates are server-side and javascript is client-side.

因此,要做的是让您的Ajax视图不返回JSON,而是返回呈现的模板,然后您的Javascript回调将其插入到模板中.

So the thing to do is to get your Ajax views not to return JSON, but rendered templates, which your Javascript callback then inserts into the template.

这篇关于在Ajax请求后返回Django模型进行模板渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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