【问题标题】:Return Django Models for Template Rendering after an Ajax Request在 Ajax 请求后返回 Django 模型以进行模板渲染
【发布时间】:2011-11-29 11:44:56
【问题描述】:

我想为我的网页创建一个基于 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})

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 %}

目前,我在页面上看到的只是“哈哈”。

【问题讨论】:

    标签: ajax django jquery django-models django-templates


    【解决方案1】:

    您缺少的是在触发 AJAX 时模板已经呈现 - 当然它必须是,因为模板是服务器端的,而 javascript 是客户端的。

    所以要做的事情是让你的 Ajax 视图不返回 JSON,而是呈现模板,然后你的 Javascript 回调将其插入到模板中。

    【讨论】:

    • 感谢您的建议。我使用了 render_to_string,然后以 {'html':html} 格式将渲染后的 html 以 json 格式发回,然后如果成功函数的参数名称称为 data,则可以通过 data.html 访问它。
    【解决方案2】:

    这是最终的答案

    蟒蛇

    if request.is_ajax():
        if request.method == 'POST':
            format = 'json'
            mimetype = 'application/json'
            try:
                q = request.POST['obj']
                #message = {"object_name": "hey, you made it"}
                o = Object.objects.filter(name__icontains=q)
            except:
                message = {"object_name": "didn't make it"}
            #m = str(q['id'])
            #json = simplejson.dumps(message)
            #data = serializers.serialize(format, o)
            #return HttpResponse(data, mimetype)
    
            html = render_to_string( 'results.html', { 'username': request.user.username, 'objects': o } )
            res = {'html': html}
            return HttpResponse( simplejson.dumps(res), mimetype )
    

    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",
                success: function( data ){
                        $( '#results' ).html( data.html );
                    }
                });
        });});
    </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 />
    <aside id="results">
    </aside>
    

    【讨论】:

      【解决方案3】:

      我的解决方案是使用 Dajax,创建小的片段模板,例如渲染列表。然后在 Dajax 函数中呈现它们,并使用适当的 javascript 调用将它们写入文档中。你可以看到一个例子(实际上所有 dajax 的文档都很好): http://www.dajaxproject.com/pagination/

      我最近发现的另一个解决方案(但我自己没有尝试过)是: http://www.jperla.com/blog/post/write-bug-free-javascript-with-pebbles

      最后你可能会完全用另一种方式使用 Backbone.js,但这样你(或多或少)最终会遇到同样的问题,如何与 django 模板共享主干模板(我认为你应该能够编写一个模板标签,它依赖于“模式”写入一个值或主干模板标签,从而允许您重用模板)

      【讨论】:

      • 谢谢我真的在寻找一个使用 Django 模板的解决方案,就像他们应该使用的那样。
      • 那么我会使用前两种解决方案之一。
      猜你喜欢
      • 2022-09-27
      • 2018-11-25
      • 1970-01-01
      • 2015-11-14
      • 2017-03-18
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 2018-11-30
      相关资源
      最近更新 更多