Search code examples
pythonajaxjsondjangocontent-type

Where's my JSON data in my incoming Django request?


I'm trying to process incoming JSON/Ajax requests with Django/Python.

request.is_ajax() is True on the request, but I have no idea where the payload is with the JSON data.

request.POST.dir contains this:

['__class__', '__cmp__', '__contains__', '__copy__', '__deepcopy__', '__delattr__',
 '__delitem__', '__dict__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
 '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__setitem__', '__str__', '__weakref__', '_assert_mutable', '_encoding', 
'_get_encoding', '_mutable', '_set_encoding', 'appendlist', 'clear', 'copy', 'encoding', 
'fromkeys', 'get', 'getlist', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 
'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update', 
'urlencode', 'values']

There are apparently no keys in the request post keys.

When I look at the POST in Firebug, there is JSON data being sent up in the request.


Solution

  • If you are posting JSON to Django, I think you want request.body (request.raw_post_data on Django < 1.4). This will give you the raw JSON data sent via the post. From there you can process it further.

    Here is an example using JavaScript, jQuery, jquery-json and Django.

    JavaScript:

    var myEvent = {id: calEvent.id, start: calEvent.start, end: calEvent.end,
                   allDay: calEvent.allDay };
    $.ajax({
        url: '/event/save-json/',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: $.toJSON(myEvent),
        dataType: 'text',
        success: function(result) {
            alert(result.Result);
        }
    });
    

    Django:

    def save_events_json(request):
        if request.is_ajax():
            if request.method == 'POST':
                print 'Raw Data: "%s"' % request.body   
        return HttpResponse("OK")
    

    Django < 1.4:

      def save_events_json(request):
        if request.is_ajax():
            if request.method == 'POST':
                print 'Raw Data: "%s"' % request.raw_post_data
        return HttpResponse("OK")