1

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?

1 Answer 1

3

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.

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

6 Comments

type(request.body) is still <class 'bytes'>
just fixed a typo (had = instead of :). how about now?
additionaly, you might try using/importing simplejson rather than json in your django view
Yeah, switched out for simplejson and now it works ;)
If you want to add that to your answer, I'll accept it ;)
|

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.