Django returning JSON for AJAX requests

In your 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.

22 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.

  10. Hi Rayed,

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

    I am implementing pagination using ajax_views.
    For that , I have written function defination in and from function sending response as ‘HttpResponse’ from that function.
    And in the I have sending NULL request because I want to render the data from ajax_views.
    In the ,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 with some sample code so others can help to resolve the issue.

  12. hi,
    what’s the main difference of using JsonResponse from DRF? JsonResponse seems to provide what i need in my new project. While DRF seems to have a longer learning curve.

  13. Hi there!
    Here’s the javascript file of current weather data, and I want to return it in a specific div in my index.html using python, how do I do that! please! please! Thank you.


    var city = $(“#city”).val();

    if(seach !=”){


    url: ‘’ + city + “&units=metric” + “&APPID=1997db27284ddfd5839f641145343f75”,
    type: “GET”,
    success: function(data){
    var widget = show(data);




    $(‘#error’).html(“×Field cannot be empty”);


    function show(data){
    return “Current Weather for “+ +”, “+ +”” +
    Weather:”+[0].main +”” +
    Description:”+[0].description +””+
    Temperature:”+ data.main.temp +”°C”+
    Pressure:”+ data.main.pressure +”hPa”+
    Humidity:”+ data.main.humidity +”%”+
    Min. Temperature:”+ data.main.temp_min +”°C”+
    Max. Temperature:”+ data.main.temp_max +”°C”+
    Wind Speed:”+ data.wind.speed +”m/s”+
    Wind Direction:”+ data.deg +”°”;

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.