Django returning JSON for AJAX requests

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

from django.http import JsonResponse

def ajax(request):
    data = {}
    data['something'] = 'useful'
    return JsonResponse(data)

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')

If you have non trivial application, I would recommend using Django Rest Framework or similar frameworks for better support for REST beyond simple JSON response.

20 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) { 
          alert(result.error_text);
        } else {  // Success
          $('#output').show();
          document.getElementById('output-ans').innerHTML=result;
          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 %}
    {{listing.name}}
    {% 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?
    Thanks.

  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.

  10. Hi Rayed,

    I have question on views and ajax-view communication through urls.py files.

    I am implementing pagination using ajax_views.
    For that , I have written function defination in ajax_views.py and from function sending response as ‘HttpResponse’ from that function.
    And in the views.py I have sending NULL request because I want to render the data from ajax_views.
    In the urls.py ,I have mapped the ,URL maps to forward the supported URLs.

    Ajax_views is working fine and data able to see on ajax_views, but the issue that in views, I am not getting the data from ajax_views. view is shows empty page.

    What exactly it missing can you provide your valuable inputs here.

    Could you please help me on this.

    Thanks in advance .

  11. Sorry, @Anil I didn’t understand the question, I would also recommend posting it in stackoverflow.com with some sample code so others can help to resolve the issue.

Leave a Reply

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