将表单数据从Angular发送到Django

时间:2014-05-13 23:55:21

标签: django angularjs

我正在尝试将一些数据从AngualrJS发布到Django后端。

我的代码如下所示:

$http({
    method: 'POST',
    url: 'path/to/django/',
    data: $scope.formData,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
});

django视图

import json

class MyView(View):
    def post(self, request):
        body = json.loads(request.body)
        # Do stuff

但是,json模块抱怨:

TypeError: the JSON object must be str, not 'bytes'

为什么数据不是作为JSON发送的,我应该如何最好地将有效负载转换为Python对象?

1 个答案:

答案 0 :(得分:3)

Content-type更改为application/json

headers: {
    'Content-Type': 'application/json'
}

值得注意的是,默认的角度$http POST行为是将数据作为JSON发送。因此,另一种策略可能是从您的headers来电中删除$http

此外,您可能希望使用simplejson而不是json

以下解释来自this question

jsonsimplejson,添加到python stdlib中。但是由于在{2.6}中添加了jsonsimplejson具有处理更多Python版本(2.4 +)的优势。

simplejson也比Python更频繁地更新,因此如果您需要(或想要)最新版本,最好尽可能使用simplejson