Django returning JSON for AJAX requests

In your you can have a page that return JSON data for AJAX request like this:

import json
from django.http import HttpResponse

def ajax(request):
    data = {}
    data['something'] = 'useful'
    return HttpResponse(json.dumps(data), content_type = "application/json")

This would work fine if you fill the data your self, but if you are getting the data from a model try the following:

from django.core import serializers
def tasks_json(request):
    tasks = Task.objects.all()
    data = serializers.serialize("json", tasks)
    return HttpResponse(data, content_type='application/json')

18 thoughts on “Django returning JSON for AJAX requests”

  1. Hello brother! 🙂
    I love your blog… please keep it updated.
    Can I find/follow you on social networks?

    Allah bless you.

  2. Hi Matt,

    You will need to write JavaScript inside your template, e.g. in jQuery you could write something like:

    function request_ajax()

    var req = $.ajax({
    url: "/django/ajax",
    dataType: "json"
    req.done(function(json_data) {
    // do something with your data


  3. ‘csrfmiddlewaretoken’: ‘{{csrf_token}}’

    pass in Jquery data :{‘csrfmiddlewaretoken’: ‘{{csrf_token}}’}

  4. $.ajax({  
      url: '/',  
      type: 'POST',
      data: { code: code, lan: lang, input1:input1},
      success: function(response) {
        result = JSON.parse(response); 
        if (result.error) { 
        } else {  // Success
          print 'yes';                                                                         
        } // end if 
        } //end function
    } // end ajax

    and then checking whether the request.is_ajax in view is giving false. Can you please tell me the reason for this?

  5. @purva It hard to tell with very limited data, stackoverflow had many question related to is_ajax not working, did you search for solution on it?

  6. I am passing a Django QuerySet to my template after serializing it to JSON as you have shown. Can I update an existing QuerySet that I had passed to the template using render_to_response() from the view that originally renders the template. Both the querysets are from the same model. Basically, I am using template tags to display attributes of the model instances in the queryset.
    So, for example:
    {% for listing in results %}
    {% endfor %}
    So results is the original queryset, I need to update it. I have the objects in JSON format. How should I go about doing this?

  7. Sorry @suhail but I didn’t get your question.

    Why would you want to send a JSON to Django template, if you want to render something in Django template you should pass the object as is.

    You would serialize to JSON if you want access the data from JavaScript from the client browser directly.

  8. Thanx Rayed, I follow your blog and I love it. It is really great.
    But how can I read that data into a table in the template.

  9. @Kenneth If you use Ajax + REST you should render the table in the client (browser) using JavaScript, and you wouldn’t use Django templates at all.

    Alternatively you could use Ajax to fetch HTML directly in this case you would render the table in the server using Django templates.

Leave a Reply

Your email address will not be published. Required fields are marked *