Django Post request not receiving data

I've spent hours looking up this issue with no avail.

I am having issue with post data from an html page I am sending {'username': 'username'} but when I do request.POST.get('username') it returns none, I alos tried {username, 'username'}

def test_post(request):
    if request.method == 'POST':
        print(request.POST.get('username'))
        return HttpResponse("Good!")
    else:
        return HttpResponse("Bad.")

Console Development Server

None <<<<

[12/Feb/2018 19:39:53] "POST /test_post HTTP/1.1" 200 5
(edited)

I am sending the data as {'username': 'username'} That works correctly how come I am unable to get it to show up?

This is the Javascript code that calls from the page:

document.getElementById('submit').addEventListener('click', function(e) {
    e.preventDefault();
   var username = document.getElementById("username").value;

   data = {username: username};
   console.log(data);
   var request = new XMLHttpRequest();
   request.open('POST', '/getuser', true);
   request.setRequestHeader('Content-Type', 'x-www-form-urlencoded');
   request.send(data);
});

1 answer

  • answered 2018-02-13 01:23 abybaddi009

    In the django view test_post, request.POST is a Query Dict (aka Dictionary).

    When you use the method .get(key), it looks for the key in the dictionary and returns you the value corresponding to the key.

    In the test_post method, you have written request.POST.get('username') which means the string 'username' as a key should be present in the POST dictionary.


    When you do a POST using Javascript, and do data = {username: username}; you are essentially making the key dynamic.

    Eg. when you input "Bob" in username and click on submit, the variable data will be {'Bob': 'Bob'}

    Instead you should do:

     data = {'username': username}        //This ensures that the key remains same