How to return json dictionary in django ajax update

ajax, django, javascript, json, python

Solution

You'll need to export your object list to a JSON dictionary.

if request.path == "/sort/":
    sortid = request.POST.get('sortid')
    locs = Location.objects.order_by(sortid)
    if request.is_ajax():
        import json
        return HttpResponse(json.dumps(locs), mimetype="application/json")

However, that's gonna require you use some type of client-side template system.

A better way is to use Django's `render_to_response` shortcut. You don't actually "need" to respond with JSON. You can just respond to the request with a string.

I usually create two templates for AJAX-powered things. The first is a partial template, which contains only the specific bit of HTML that I would want to update during an AJAX-updated. The second is a wrapper, which can be used when the view is called normally.

A cheap example, here's my object_list.html:

<ul id='object-list'>
    {% for object in object_list %}
        <li>{{ object.value }}</li>
    {% endfor %}
</ul>

And here's my base.html:

<html>
<title>Example</title>
    <body>
        {% include 'object_list.html' %}
    </body>
</html>

For the view, you'll want to do this:

from django.shortcuts import render_to_response
from django.template import RequestContext

from models import Location

def view(request):
    locs = Location.objects.order_by(sortid)
    if request.is_ajax():
        return render_to_response('object_list.html', {'object_list': locs}, context_instance=RequestContext(request))
    return render_to_response('base.html', {'object_list': locs}, context_instance=RequestContext(request))

This let's the view get called normally, via a standard GET, or via an XHTTP request, returning only the partial HTML you want to update. Handy!

Problem

i am asking this question multiple times since i have not received any applicable help. my problem is that i dont know how to return query result to template as an ajax response. i did this: ``` if request.path == "/sort/": sortid = request.POST.get('sortid') locs = Location.objects.order_by(sortid) if request.is_ajax(): return HttpResponse(locs,mimetype="application/json") ``` then my ajax `done` function does this: ``` }).done(function(data){ $('.sortierennach').html(data); }); ``` what now happens is that it just replaces the content of `.sortierennach`, it is not rendering django dic so that i can do this: ``` {% for loc in locs %} {{loc.name}} {% endfor %} ``` can someone please help me... thanks a lot

Original source