how to render only part of html with data using django

邮差的信 提交于 2019-12-03 06:13:55

问题


I am using ajax to sort the data which came from search results.

Now I am wondering whether it is possible to render just some part of html so that i can load this way:

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

I am doing this but I am getting the whole html page as response and it is appending the whole html page to the existing page which is terrible.

this is my 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))

how can I render only that <div id="result"> </div> from my view function? or what am I doing here wrong?


回答1:


From what I understand you want to treat the same view in a different way if you receive an ajax request. I would suggest splitting your result-page.html into two templates, one that contains only the div that you want, and one that contains everything else and includes the other template (see django's include tag).

In your view then you can do something like the following:

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))

results-page.html:

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

partial-results.html:

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


来源:https://stackoverflow.com/questions/16110099/how-to-render-only-part-of-html-with-data-using-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!