marisbest2
marisbest2

Reputation: 1356

Respond to AJAX with Django template rendered

I want to be able to return fully rendered templates to an ajax call. For example:

segment.html

<div class="swappable_segment" id="{{ id }}">
    {% for object in objects %}
        <li>Some text</li>
    {% endfor %}
</div>

views.py

def f(request):
    return SOMETHING

There should be ajax code such that when I press a button on a page, it swaps out the old div with a newly rendered div.

I know how to do the AJAX part, but I'm wondering what the function f should return. I'm thinking it should return an HttpResonse object with JSON with the html of the new div, but I dont know how to actually render it.

Upvotes: 2

Views: 3168

Answers (1)

mishbah
mishbah

Reputation: 5597

How about something like this:

from django.template.loader import render_to_string

def f(request):

    [...] #logic here to get objects_list

    if request.is_ajax():
        html = render_to_string('path/to/your/segment.html', {'objects': objects_list})
        return HttpResponse(html)

Docs: https://docs.djangoproject.com/en/1.7/ref/templates/api/#the-render-to-string-shortcut

Upvotes: 3

Related Questions