10

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 Answer 1

22

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 %}
Sign up to request clarification or add additional context in comments.

1 Comment

That's simple & clever

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.