【发布时间】:2012-10-01 04:06:20
【问题描述】:
我正在尝试使用 angular.js 对此 Django 视图创建 POST 请求。
class PostJSON4SlickGrid(View):
"""
REST POST Interface for SlickGrid to update workpackages
"""
def post(self, request, root_id, wp_id, **kwargs):
print "in PostJSON4SlickGrid"
print request.POST
return HttpResponse(status=200)
因此我创建了这个资源。
myModule.factory('gridData', function($resource) {
//define resource class
var root = {{ root.pk }};
return $resource('{% url getJSON4SlickGrid root.pk %}:wpID/', {wpID:'@id'},{
get: {method:'GET', params:{}, isArray:true},
update:{method:'POST'}
});
});
在控制器中调用 get 方法可以正常工作。该网址被翻译为http://127.0.0.1:8000/pm/rest/tree/1/。
function gridController($scope, gridData){
gridData.get(function(result) {
console.log(result);
$scope.treeData = result;
//broadcast that asynchronous xhr call finished
$scope.$broadcast('mySignal', {fake: 'Hello!'});
});
}
虽然我在执行更新/POST 方法时遇到问题。
item.$update();
URL 被转换为http://127.0.0.1:8000/pm/rest/tree/1/345,缺少尾部斜杠。如果在 URL 定义中不使用尾部斜杠,则可以轻松避免这种情况。
url(r'^rest/tree/(?P<root_id>\d+)/(?P<wp_id>\d+)$', PostJSON4SlickGrid.as_view(), name='postJSON4SlickGrid'),
而不是
url(r'^rest/tree/(?P<root_id>\d+)/(?P<wp_id>\d+)/$', PostJSON4SlickGrid.as_view(), name='postJSON4SlickGrid'),
使用不带斜杠的解决方法,我现在得到一个 403(禁止)状态代码,这可能是因为我没有在 POST 请求中传递 CSRF 令牌。因此,我的问题归结为如何将 CSRF 令牌传递到 Angular 创建的 POST 请求中?
我知道 this 通过标头传递 csrf 令牌的方法,但我正在寻找一种可能性,以将令牌添加到发布请求的正文中,正如 here 所建议的那样.是否可以在 Angular 中将数据添加到发布请求正文?
作为其他阅读材料,您可以查看这些关于资源、删除尾部斜杠以及资源当前存在的限制的讨论:disc1 和disc2。 在一次讨论中,一位作者建议目前不要使用资源,而是使用this 方法。
【问题讨论】: