Deepankar Bajpeyi Deepankar Bajpeyi - 5 months ago 74
AngularJS Question

Sending post data from angularjs to django as JSON and not as raw content

I have a request like this:

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


In my django views:

class SomeClass(View):
def get(self, request):
return HttpResponse("Hello")
def post(self, request):
print request.post
print request.body
return HttpResponse("Done")


So when I do
request.POST
I get an empty query dict :
<QueryDict: {}>


But my
request.body
has:
test=data


So I believe django receives the data as url-encoded parameters and not as a dictionary.

How do I send or receive this data as JSON/Dict ?

Answer

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)