Angularjs django rest框架注释表单不工作

Angularjs django rest框架注释表单不工作,angularjs,django,django-rest-framework,Angularjs,Django,Django Rest Framework,我使用django rest框架创建了这个站点,这样它就可以在不刷新页面的情况下工作 使用angular js的路由功能是构建单页应用程序的最佳选择 但出于某种原因,注释框似乎不起作用,可能是因为它被放在angular js的模板中 它向我抛出csrf令牌丢失错误,即使包含该令牌 根据{%csrf token%}标记作为文本可见这一事实判断,我认为angular模板无法读取django标记 有人能告诉我为什么评论表单不起作用,以及我如何解决这个问题吗 (function() { a

我使用django rest框架创建了这个站点,这样它就可以在不刷新页面的情况下工作

使用angular js的路由功能是构建单页应用程序的最佳选择

但出于某种原因,注释框似乎不起作用,可能是因为它被放在angular js的模板中

它向我抛出csrf令牌丢失错误,即使包含该令牌

根据{%csrf token%}标记作为文本可见这一事实判断,我认为angular模板无法读取django标记

有人能告诉我为什么评论表单不起作用,以及我如何解决这个问题吗

    (function() {
  angular.module('app', ['ngRoute', 'ngResource'])
.controller('FilesListCtrl', ['$scope','$http', function($scope, $http) {//this one controller is new


  angular.forEach($scope.posts, function(_post){
    $scope.styles = producePostStyle(_post)
  });
  function producePostStyle(post) {
    return { "background-image": "url(" + post.image + ")" }
  }
$scope.producePostStyle = producePostStyle;
  $http.get('/api/posts/').then(function (response) {
              $scope.viewStyle = {
                  background: 'url('+response.data.results.image+')'
              };

  });

    $scope.images = [];
    $scope.next_page = null;
    var in_progress = true;

    $scope.loadImages = function() {
    //alert(in_progress);
            if (in_progress){
            var url = '/api/posts/';//api url
            if ($scope.next_page) {
                url = $scope.next_page;
            }
            $http.get(url).success(function(data) {
                $scope.posts = $scope.posts.concat(data.results);//according to api
                $scope.next_page = data.next;//acccording to api

                if ( ( $scope.next_page == null ) || (!$scope.next_page) ) {
                    in_progress = false;
                }
            });
        }
    };

    $scope.loadImages();
}])
angular.module('app')
.controller('profile_image', ['$scope','$http', function($scope, $http) {//this one controller is new

  $http({
    url: '/api/users/profile/',
    method: "GET",
    params: {username: 'lifeto'}
}).then(function successCallback(response) {
    console.log("Profile Image");
    console.log(response);
    $scope.lifeto_img = response.data;
}, function errorCallback(response) {
    console.log("Error fetching profile image!");
});

}])




.directive('whenScrolled', function($document) {//another directive
        return function(scope, elm, attr) {
            var raw = elm[0];

             $document.bind('scroll', function() {
                if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
                    scope.$apply(attr.whenScrolled);
                }
            });
        };
    })
    .config(function($resourceProvider, $routeProvider, $httpProvider) {
      $httpProvider.defaults.xsrfCookieName = 'csrftoken';
      $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
      // Don't strip trailing slashes from calculated URLs
      $resourceProvider.defaults.stripTrailingSlashes = false;
      $routeProvider
        .when('/', {
          template: '<posts></posts>'
        })
        .when('/posts', {
          template: '<posts></posts>'
        })
        .when('/post/:postId', {
          template: '<post></post>'
        })
        .otherwise({
          redirectTo: '/'
        });
    });
  angular.module('app')
    .constant('API_URL', '/api/posts/');
  angular.module('app')
    .factory('Posts', function($resource, API_URL) {
      return $resource(API_URL, {format: 'json'}, {
        queryPosts: {
          method: 'GET',
          isArray: false
        },
        getPostInfo: {
          url: API_URL + ':postId/',
          method: 'GET',
          isArray: false,
          params: {
            postId: '@postId',
            format: 'json'
          }
        }
      });
    });
  angular.module('app')
    .directive('post', function() {
      return {
        restrict: 'E',
        templateUrl: '/static/post.html',
        scope: {},
        controller: function($scope, $routeParams, Posts) {
          $scope.post = null;

          function clean(id) {
        return id.toLowerCase().replace(/\s/g, "-");
      }

      function _initialize() {
   Posts.getPostInfo({
     postId: clean($routeParams.postId)
   })
              .$promise
                .then(function(result) {
                  $scope.post = result;
                  console.log(result)
                });
          }
          _initialize();
        }
      };
    });
  angular.module('app')
    .directive('posts', function() {
      return {
        restrict: 'E',
        templateUrl: '/static/posts.html',
        scope: {},
        controller: function($scope, Posts) {
          $scope.posts = [];
          function _initialize() {
            Posts.queryPosts().$promise.then(function(result) {
              $scope.posts = result.results;
            });
          }
          _initialize();
        }
      };
    });
})();
(函数(){
角度.module('app',['ngRoute','ngResource']))
.controller('filelistctrl',['$scope','$http',函数($scope,$http){//这一个控制器是新的
angular.forEach($scope.posts,function(\u post){
$scope.styles=producePostStyle(\u post)
});
函数producePostStyle(post){
返回{“背景图像”:“url(“+post.image+”)}
}
$scope.producePostStyle=producePostStyle;
$http.get('/api/posts/')。然后(函数(响应){
$scope.viewStyle={
背景:“url('+response.data.results.image+')”
};
});
$scope.images=[];
$scope.next_page=null;
var in_progress=真;
$scope.loadImages=函数(){
//警报(进行中);
如果(进行中){
var url='/api/posts/';//api url
如果($scope.next_页){
url=$scope.next_页面;
}
$http.get(url).success(函数(数据){
$scope.posts=$scope.posts.concat(data.results);//根据api
$scope.next\u page=data.next;//根据api
if($scope.next_page==null)| |(!$scope.next_page)){
进行中=错误;
}
});
}
};
$scope.loadImages();
}])
角度。模块('app')
.controller('profile_image',['$scope','$http',function($scope,$http){//这一个控制器是新的
$http({
url:“/api/users/profile/”,
方法:“获取”,
参数:{username:'lifeto'}
}).then(函数成功回调(响应){
控制台日志(“配置文件图像”);
控制台日志(响应);
$scope.lifeto_img=response.data;
},函数errorCallback(响应){
log(“获取配置文件图像时出错!”);
});
}])
.directive('whenScrolled',function($document){//另一个指令
返回函数(范围、elm、属性){
var raw=elm[0];
$document.bind('scroll',function(){
if(raw.scrollTop+raw.offsetHeight>=raw.scrollHeight){
适用范围:$apply(滚动时的附加值);
}
});
};
})
.config(函数($resourceProvider、$routeProvider、$httpProvider){
$httpProvider.defaults.xsrfCookieName='csrftoken';
$httpProvider.defaults.xsrfHeaderName='X-CSRFToken';
//不要从计算的URL中删除尾部斜杠
$resourceProvider.defaults.stripTrailingSlashes=false;
$routeProvider
。当(“/”{
模板:“”
})
。当(“/posts”{
模板:“”
})
.when('/post/:posted'{
模板:“”
})
.否则({
重定向到:'/'
});
});
角度。模块('app')
.constant('API_URL','/API/posts/');
角度。模块('app')
.factory('Posts',函数($resource,API_URL){
返回$resource(API_URL,{格式:'json'}{
查询栏:{
方法:“GET”,
艾萨瑞:错
},
getPostInfo:{
url:API_url+':postId/',
方法:“GET”,
艾萨瑞:错,
参数:{
postId:“@postId”,
格式:“json”
}
}
});
});
角度。模块('app')
.directive('post',function(){
返回{
限制:'E',
templateUrl:“/static/post.html”,
作用域:{},
控制器:功能($scope,$routeParams,Posts){
$scope.post=null;
功能清洁(id){
返回id.toLowerCase().replace(/\s/g,“-”);
}
函数_initialize(){
Posts.getPostInfo({
posted:clean($routeParams.posted)
})
.$承诺
.然后(函数(结果){
$scope.post=结果;
console.log(结果)
});
}
_初始化();
}
};
});
角度。模块('app')
.directive('posts',function(){
返回{
限制:'E',
templateUrl:“/static/posts.html”,
作用域:{},
财务主任:职能(范围、职位){
$scope.posts=[];
函数_initialize(){
Posts.queryPosts().$promise.then(函数(结果){
$scope.posts=result.results;
});
}
_初始化();
}
};
});
})();
自从您添加

$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$http将负责csrf

现在,您可以使用
$http

$http({
    method: 'POST',
    url: '/url/',
    data: {
        "key1": 'value1',
    },
}).then(function successCallback(response) {
    #do
    },
    function errorCallback(response) {
    #do
    });

注意:不要在此处使用Ajax帖子。为此,除此之外,您还需要做一些csrf工作。

谢谢您的回答。但我对angular js还不熟悉,很难弄清楚该把它放在哪里,怎么放。这是正确的吗?它仍然向我抛出同样的csrf丢失错误。(什么进入“数据”)?将app.js也粘贴到dpast中。这是整个app.js。如果你是指index.html的ajax代码,我也可以给你。我的回答是,在控制器中使用
$http
将函数上的
$(“#注释_表单”)更改为代码。谢谢你。但我已经试过了,它仍然抛出csrf令牌丢失或错误错误(