在Ajax请求后返回Django模型进行模板渲染

Jes*_*and 1 django ajax jquery django-templates django-models

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

这是我正在使用的代码。

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})
Run Code Online (Sandbox Code Playgroud)

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 %}
Run Code Online (Sandbox Code Playgroud)

此刻,我在页面上看到的只是“哈哈”。

Dan*_*man 5

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

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