【问题标题】:how to render only part of html with data using django如何使用 django 仅用数据呈现 html 的一部分
【发布时间】:2013-04-13 04:05:13
【问题描述】:

我正在使用 ajax 对来自搜索结果的数据进行排序。

现在我想知道是否可以只渲染 html 的一部分以便我可以这样加载:

$('#result').html(' ').load('/sort/?sortid=' + sortid);

我正在这样做,但我得到了整个 html 页面作为响应,并且它正在将整个 html 页面附加到现有页面,这很糟糕。

这是我的观点.py

def sort(request):
  sortid = request.GET.get('sortid')
  ratings = Bewertung.objects.order_by(sortid)
  locations = Location.objects.filter(locations_bewertung__in=ratings)
  return render_to_response('result-page.html',{'locs':locations},context_instance=RequestContext(request))

我怎样才能从我的视图函数中只渲染那个<div id="result"> </div>?或者我在这里做错了什么?

【问题讨论】:

    标签: python django django-templates rendering


    【解决方案1】:

    据我了解,如果您收到 ajax 请求,您希望以不同的方式处理相同的视图。 我建议将您的 result-page.html 拆分为两个模板,一个仅包含您想要的 div,另一个包含其他所有内容并包含另一个模板(请参阅 django's include tag)。

    在您看来,您可以执行以下操作:

    def sort(request):
        sortid = request.GET.get('sortid')
        ratings = Bewertung.objects.order_by(sortid)
        locations = Location.objects.filter(locations_bewertung__in=ratings)
        if request.is_ajax():
            template = 'partial-results.html'
        else:
            template = 'result-page.html'
        return render_to_response(template,   {'locs':locations},context_instance=RequestContext(request))
    

    结果页面.html:

    <html>
       <div> blah blah</div>
       <div id="results">
           {% include "partial-results.html" %}
       </div>
       <div> some more stuff </div>
    </html>
    

    部分结果.html:

    {% for location in locs %}
        {{ location }}
    {% endfor %}
    

    【讨论】:

    • 简单又聪明
    猜你喜欢
    • 1970-01-01
    • 2013-08-05
    • 2020-09-22
    • 2013-04-13
    • 2020-05-14
    • 1970-01-01
    • 2011-10-07
    • 2022-10-13
    • 1970-01-01
    相关资源
    最近更新 更多