Question

I am trying to post some data from AngualrJS to a Django backend.

My code looks like this:

angular

$http({
    method: 'POST',
    url: 'path/to/django/',
    data: $scope.formData,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
});

django view

import json

class MyView(View):
    def post(self, request):
        body = json.loads(request.body)
        # Do stuff

However, the json module complains:

TypeError: the JSON object must be str, not 'bytes'

Why is the data not sent as JSON and how should I best convert the payload to a Python object?

Was it helpful?

Solution

Change the Content-type to application/json

headers: {
    'Content-Type': 'application/json'
}

It's also worth noting that the default angular $http POST behavior is to send the data as JSON. So another strategy might be to remove headers from your $http call altogether.

Also, you may want to use simplejson rather than json

The following explanation was taken from this question:

json is simplejson, added to the python stdlib. But since json was added in 2.6, simplejson has the advantage of working on more Python versions (2.4+).

simplejson is also updated more frequently than Python, so if you need (or want) the latest version, it's best to use simplejson if possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top