Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sending data from angularjs to django

I am sending a POST AJAX request using Angularjs and its $http module to Django server. Here is an example:

$http({ 
        method: 'POST', 
        url: '/url/', 
        data: 'test data'
  }).
  success(function(data, status, headers, config) {
        doSomeStuffWhenSuccess();
  });

The problem is what I get in Django. No matter what I send the data is always the key of QueryDict object and value of that is always an empty list.

<QueryDict: {u'test data': [u'']}>

I don't have a clue why. What am I missing?

I use almost default created Django application with default middlewares only. I created only a view and set an url in url config. Version of Django is 1.3. And I configured angular's $http module to always send a header containg csrf token to satisfy Django.

like image 217
davekr Avatar asked May 09 '12 16:05

davekr


2 Answers

I resolved this with jQuery param function. I think it's more elegant solution.

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

Now it works like I wanted.

like image 64
davekr Avatar answered Sep 28 '22 06:09

davekr


I believe django thinks you are sending a urlencoded form, ex. key=value&key2=value2...

if you'd try:

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

You should get

<QueryDict: {u'test': [u'data']}>

You can always obtain the data (raw body content) as follows:

request.body

Hope this is what you are looking for.

like image 44
Krzysztof Rosiński Avatar answered Sep 28 '22 04:09

Krzysztof Rosiński