-1

I am using the following function to send JSON formatted data to my Django based server which stores the user keys generated for users in a database. When I try to access the request.body on the server side using python on Django, it gets printed as a string [object Object]. How do I handle this part of parsing the json from the request.body on server side. function completeKeygen(data) { var key_data = { 'user_id':user_id, 'keys':data } delete data['action']; console.log("Sending UBE Keys to User"); console.log(key_data);

    var oReq = new XMLHttpRequest();
    oReq.open("POST",CLOUD_SERVER+'add_ube_keys',true);
    oReq.responseType = "json";
    oReq.setRequestHeader("Content-type", "application/json");
    oReq.onload = function(oEvent){
        console.log(oReq.response.success);
    };
    oReq.send(key_data);
}

For reference the server side code:

@csrf_exempt
def add_ube_keys(request):
    data = request.POST
    print data.get('user_id')
    return_data = {
        'success':True
    }
    rdata = json.dumps(return_data)
    return HttpResponse(rdata, content_type='application/json')

Unlike the possibly duplicate question, I am getting the Querydict object on print request.POST returns <QueryDict: {}>. Why is it empty ?

4
  • 1
    possible duplicate of Django request Post json Commented Jul 15, 2015 at 9:34
  • 2
    Finding the answer on SO took me about 1'27''... Commented Jul 15, 2015 at 9:35
  • You must be a genius @brunodesthuilliers but I am a noob learner for sure, politeness alongside knowledge doesn't costs much anyways. Thanks :) Commented Jul 15, 2015 at 11:46
  • print request.POST returns <QueryDict: {}>, not the one populated as given in the question stackoverflow.com/questions/24958705/django-request-post-json Commented Jul 15, 2015 at 12:04

2 Answers 2

0

I still don't know what is wrong with my approach in the question mentioned above but I solved this in three steps:

  1. I added JSON.stringify(key_data) in the javascript before sending the XMLHttpRequest.

  2. Changed application/json to application/x-www-form-urlencoded.

  3. Now the python side treats the data as a normal string, so I used json.loads(request.body) to extract the json object from the stringified data.

The above two steps have been taken from the previously posted question: How to receive POST data in python when using XMLHttpRequest()

Sign up to request clarification or add additional context in comments.

Comments

0

request.POST only includes form data now. You'll have to parse out the JSON from request.body.

https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.POST

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.