Python 在angular-to-django视图中通过$http.post发送数组
我想将此请求发送到django视图:Python 在angular-to-django视图中通过$http.post发送数组,python,django,angularjs,Python,Django,Angularjs,我想将此请求发送到django视图: $http({ method: "post", url: "/enterprises/vouchers/_send", data: { group_id: group_id, group_student_ids: [1, 2, 3, 4] } }).success(function (response) { console.
$http({
method: "post",
url: "/enterprises/vouchers/_send",
data: {
group_id: group_id,
group_student_ids: [1, 2, 3, 4]
}
}).success(function (response) {
console.log("emails are sent. please check");
}).error(function () {
console.log("failed")
});
在视图中,我按如下方式分配它们:
group_student_ids = request.POST['group_student_ids']
group_id = request.POST['group_id']
“group_id”按预期分配,但django正在为aray对象(group_student_id)抛出多值DictKeyError
如何通过post请求发送阵列 试试这个:
group_student_ids = request.POST.getlist('group_student_ids[]')
这应该起作用:
首先,将数据更改为:
data: {
'group_id': group_id,
'group_student_ids[]': [1, 2, 3, 4]
}
在你看来:
group_student_ids = request.POST.getlist('group_student_ids[]')
编辑:
只是在我的应用程序中做了一些测试;如果我打印request.POST
,我将获得
<QueryDict: {'group_student_ids[]': ['1', '2', '3', '4']}>
而type(group\u student\u id)
会给
一个空列表[]:(@Rodrigue printrequest.POST
在视图中,你得到了什么?我得到了这个:。所以,结果是我分别得到了它们。我不知道why@Rodrigue将ajax调用中的组学生ID:[1,2,3,4]
更改为“group_student_ID[]”:[1,2,3,4]
同样的事情:我在打印请求时得到了这个。POST:@Rodrigue-修复了拼写错误;现在应该可以工作了(我在调用getlist()时使用了方括号)我不知道为什么,但它对我不起作用。无论如何,我通过将数组转换为字符串并将其拆分回django视图中的列表来解决这个问题。谢谢你的回答)@罗德里格:不客气;仍然不确定它为什么不起作用;可能与视图有关。此外,我在我的应用程序中使用jQuery的$.ajax()
而不是AngularJS进行了测试