我正在尝试使用angular.js创建一个POST请求到这个Django视图。
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方法是有效的。URL将被转换为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请求中?我知道可以使用此方法通过头文件传递csrf令牌,但我正在寻找一种将令牌添加到post请求正文中的可能性,就像这里所建议的那样。在Angular中是否有可能向post请求正文添加数据?
作为额外的阅读材料,可以查看关于资源、移除尾部斜杠以及当前资源限制的这些讨论: 讨论1 和 讨论2。在其中一个讨论中,其中一位作者建议目前不要使用资源,而是改用此方法。
$http
传递相对 URL 时才会这样做? - Akaisteph7