【问题标题】:django rest framework comment form not workingdjango rest框架评论表单不起作用
【发布时间】:2016-12-25 09:21:12
【问题描述】:

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

http://192.241.153.25:8000/#/post/image3

使用 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();
        }
      };
    });
})();

【问题讨论】:

    标签: angularjs django django-rest-framework


    【解决方案1】:

    自从你添加了

    $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 Post。为此,您必须做一些除此之外的 csrf 事情。

    【讨论】:

    • 感谢您的回答。但我是 angular js 的新手,很难弄清楚把这个东西放在哪里以及如何放置。它是否正确?它仍然给我同样的 csrf 缺失错误。 dpaste.de/54na(“数据”中有什么)?
    • 将你的 app.js 也粘贴到 dpaste 中。
    • 这是整个 Angular js。如果您的意思是 index.html 的 ajax 代码,我也可以将其提供给您。 dpaste.de/GMGF#L2
    • 我的回答是,将您的 $('#comment_form').on 函数更改为在控制器内使用 $http 的代码。 dpaste.de/4dnj
    • 谢谢。但我已经尝试过了,它仍然抛出 csrf 令牌丢失或错误错误。 :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多