0

I am sending a POST request to my server which is throwing a 500 error when my server code attempts to read data from the POST request. But the data looks perfectly ok to me.

The POST data is:

<QueryDict: {u'{"firstname":"jack","lastname":"rowley","username":"jack","email":"info@mybiz.co.uk","password":"jack","city":"London","country":"UK","photo":"","genre1":"Comedy","genre2":"Horror","genre3":"Documentary","platform":"Cinema"}': [u'']}>

The Python code that is reading the POST data is:

username = request.POST['username']
password = request.POST['password']
email = request.POST['email']

It falls over at the first line, trying to access the username.

The AngularJS code that makes the POST request looks like this:

 url = apiDomain + '/profile/register/';
      var fn = 'jack';
      var ln = 'rowley';
      var un = 'jack';
      var pw = 'jack';
      var cf = 'jack';
      var em = 'info@mybiz.co.uk';
      var lc = 'London';
      var ct = 'UK';
      var ph = '';  //$('#photo_set').val();
      var genre1 = 'Comedy';
      var genre2 = 'Horror';
      var genre3 = 'Documentary';
      var platform = 'Cinema';

      return $http({
        method: 'POST',
        url: url,
        headers: {
          'Content-Type': "application/x-www-form-urlencoded"
        },
        data: {
          firstname: fn,
          lastname: ln,
          username: un,
          email: em,
          password: pw,
          city: lc,
          country: ct,
          photo: ph,
          genre1: genre1,
          genre2: genre2,
          genre3: genre3,
          platform: platform
        }
      }).then(function successCallback(response) {
        return response;
      }, function errorCallback(response) {
        return -1;
      });
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
Bill Noble
  • 6,466
  • 19
  • 74
  • 133

2 Answers2

3

You are trying to access this data as if it were form-encoded. It is not; it is JSON.

You need to access the raw post body, and decode it from JSON.

data = json.loads(request.body)
username = data['username']
password = data['password']
email = data['email']
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

You're getting a KeyError because you don't have a username.

Your query dict is not a dict. It's a single-item string key, with an empty-string value. The key happens to be a string-encoding of some url encoding string. Look at it.

 QueryDict: { u'{"fi text text text': u'' }

You are passing a URL-encoded string where you should be passing a dict, probably in the client.

Chad Miller
  • 1,435
  • 8
  • 11
  • Thanks Chad your advice helped me home in on the problem and I found a solution for the client side problem here: http://stackoverflow.com/questions/24710503/how-do-i-post-urlencoded-form-data-with-http-in-angularjs – Bill Noble Oct 08 '15 at 16:05