3

I'm newbie to django. I'm creating a simple app that posts user data to Django server. But I'm facing a problem regarding queryDict. It's empty. The code is:

@csrf_exempt
def create_user(request):
    """
    This function creates users
    :param request: post request from front-end
    :return: success/failure
    """
    if request.method == 'POST':
        #x = json.loads(request.POST)
        print(request.POST)
        return JSONResponse(request.POST)

The POST request is :

function post(){
    xmlhttp = new XMLHttpRequest();
    var url = "http://127.0.0.1:8000/create_user/";
    xmlhttp.open("POST", url, true);
    //xmlhttp.setRequestHeader("Content-type", "application/json");
    xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert(xmlhttp.responseText);
        }
    }
    var parameters = {
        "username": "myname",
        "password": "mypass"
    };
    xmlhttp.send(JSON.stringify(parameters));
}
SashaZd
  • 3,279
  • 1
  • 21
  • 48
pnv
  • 2,545
  • 3
  • 26
  • 35

3 Answers3

12

You're sending data in the body of the request:

xmlhttp.send(JSON.stringify(parameters));

This data will then end up in the request.body.

This is not the same as POSTing a HTML form, so it won't end up in the request.POST. If you want to simulate a HTML form POST, see this answer.

Community
  • 1
  • 1
gitaarik
  • 31,690
  • 11
  • 86
  • 92
5

Your JSON object should be hidden in request.body so you can then access the properties of the object:

request.body["username"]
request.body["password"]
justcompile
  • 2,922
  • 1
  • 25
  • 35
  • 1
    You have to first parse the values by data = json.loads(request.body) Then you can access it by property names. Eg: data["username"] – Mehul Tandale Mar 17 '18 at 11:35
1

Coming here late but let me put my observation as well. Your data will go into the body. But depending on your python version the method to access it will differ. As the body data will come in form of bytes in Python3+ and as a string in Python2.7 So you have to keep in mind how are you going to access it

Python3

form_data = json.loads(request.body.decode())

Python2.7

form_data = json.loads(request.body)
Ishan Bhatt
  • 5,940
  • 5
  • 16
  • 37