5

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.

2 Answers 2

7

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.

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

Comments

6

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.

2 Comments

Thanks this works! But could you explain why django thinks its urlencoded data? And if its possible to customize it?
request.GET and request.POST contain preprocessed key/value data - if you want raw data (such as JSON or plain text) try: request.raw_post_data

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.