don*_*yor 10 python django rendering django-templates
我正在使用ajax对来自搜索结果的数据进行排序.
现在我想知道是否有可能只呈现html的某些部分,以便我可以这样加载:
$('#result').html(' ').load('/sort/?sortid=' + sortid);
我这样做,但我得到整个html页面作为响应,它是将整个html页面附加到现有的页面,这很糟糕.
这是我的views.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>从我的视图函数中渲染它?或者我在这做错了什么?
Gee*_*ish 19
根据我的理解,如果收到ajax请求,您希望以不同的方式处理相同的视图.我建议将你result-page.html分成两个模板,一个只包含你想要的div,另一个包含其他所有模板,包括另一个模板(参见django的include标签).
在您的视图中,您可以执行以下操作:
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))
结果-page.html中:
<html>
   <div> blah blah</div>
   <div id="results">
       {% include "partial-results.html" %}
   </div>
   <div> some more stuff </div>
</html>
局部results.html:
{% for location in locs %}
    {{ location }}
{% endfor %}