[Django]-Sending post data from angularjs to django as JSON and not as raw content

44👍

When calling ajax, you recieve encoded json string in request body, so you need to decode it using python’s json module to get python dict:

json.loads(request.body)

14👍

In my case works something like

$http({
    url: '/url/',
    method: "POST",
    data: $.param(params),
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
})

Or more nice variant:

app.config ($httpProvider) ->
    ...
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

and then

$scope.save_result = $http.post('/url/', $.param(params))

http://www.daveoncode.com/2013/10/17/how-to-make-angularjs-and-django-play-nice-together/

2👍

I am using zope2 where I used simplejson to decode the request json into python dictionary as:

request_dict = simplejson.loads(request.get('BODY','')

It’s working correctly for me. In this way I am able to use angularjs default json request rather than converting it into form post.

2👍

I improved mariodev’s solution a bit by creating a decorator:

# Must decode body of angular's JSON post requests
def json_body_decoder(my_func):
    def inner_func(request, *args, **kwargs):
        body = request.body.decode("utf-8")
        request.POST = json.loads(body)
        return my_func(request, *args, **kwargs)
    return inner_func

 @json_body_decoder
 def request_handler(request):
     # request.POST is a dictionary containing the decoded body of the request

Now I just add the @json_body_decoder decorator whenever I create a request handler that deals with post data in application/json.

1👍

For angular 4 and Django Rest Framework use request.data to get json object.

like:

posted_data = request.data

0👍

The $http service expects a JS object, not a string. Try this:

$http({ 
    method: 'POST', 
    url: '/url/', 
    data: {test: 'data'}
})

Leave a comment