Skip to content Skip to sidebar Skip to footer

How To Loop Ajax Response Data In Django Template Language?

i am new to Django,recently meet a problem :as we know , to loop a data sent by view in html is simple , like below: {% for key in data %}

{{ key }}

{% endfo

Solution 1:

You need to use JsonResponse in your view.

>>>from django.http import JsonResponse>>>response = JsonResponse({'foo': 'bar'})>>>response.content
b'{"foo": "bar"}'

or for dict

response = JsonResponse([1, 2, 3], safe=False)

https://docs.djangoproject.com/en/3.0/ref/request-response/

en than with jQuery

success: function (data) {
   $.each(data.data, function(k, v) {
       /// do stuff
   });
}

Solution 2:

An alternative approach to what NKSM has suggested would be to return a partial view and inject the html in.

Your view:

defprocess_data(request):
    return render(request, 'partials/process_data.html', context={
        'data': [1, 2, 3],
    })

partials/process_data.html template

{% for key in data %}
    <p>{{ key }}</p>
{% endfor %}

Then your loading JS turns into

var container = $('#some-container')
container.load('/processData', {foo: "this is required to force a post rather than get")

Post a Comment for "How To Loop Ajax Response Data In Django Template Language?"