Как в ангулар реализовать $http.post в такой json?

Привет, у меня spa-приложение, к каждому посту есть комментарии, вот такой json стандартного коммента:
{
        "comments_text": "adfasdfasdf",
        "comments_post": {
            "id": 18,
            "title": "asdfasdf",
            "image": null,
            "height_field": 0,
            "width_field": 0,
            "content": "asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf asdfasdf vv",
            "check": true,
            "updated": "2016-05-25 в 18:13",
            "timestamp": "2016-05-25 в 18:13",
            "user": {
                "id": 1,
                "password": "pbkdf2_sha256$24000$kSUmB51QpUSi$yWJZJt539Mj7+TLGz1tS+uIMk9dHs766opPlw8FEX0E=",
                "last_login": "2016-05-27 в 16:39",
                "is_superuser": true,
                "username": "test",
                "first_name": "",
                "last_name": "",
                "email": "test@gmail.com",
                "is_staff": true,
                "is_active": true,
                "date_joined": "2016-05-25 в 10:33",
                "groups": [],
                "user_permissions": []
            }
        },

Контроллер:

var myApp = angular.module('myApp',['ui.bootstrap']);

myApp.run(function($http) {
  $http.defaults.xsrfCookieName = 'csrftoken';
  $http.defaults.xsrfHeaderName = 'X-CSRFToken';
});

myApp.controller('PostsListController', ['$scope','$http',function($scope,$http) {
  $http.get('/api/v1/posts/').success(function (data) {

$scope.posts = data;
$scope.filteredPosts = [];
$scope.currentPage = 1;
$scope.numPerPage = 5;
$scope.maxSize = 5;
$scope.checked = 0;

$scope.numPages = function () {
    return Math.ceil($scope.posts.length / $scope.numPerPage);
  };

$scope.$watch('currentPage + numPerPage', function() {
    var begin = (($scope.currentPage - 1) * $scope.numPerPage);
    var end = begin + $scope.numPerPage;
    $scope.filteredPosts = $scope.posts.slice(begin, end);

  });

  });

$scope.deletePost = function(post) {
      $scope.confirm = confirm('Хотите удалить статью?');
      if($scope.confirm){
            $http.delete('/api/v1/posts/'+ post.id + '/');
            $scope.filteredPosts.splice($scope.filteredPosts.indexOf(post), 1);
            $scope.posts.splice($scope.posts.indexOf(post), 1);
      }

    };

$http.post('/posts/check_login/').success(function(data){
    $scope.user = data;
  });

$http.get('/api/v1/comments/').success(function (data) {
   $scope.comments = data;
});


$scope.postComment = function(comment) {
             $http.post("/api/v1/comments/", {'comments_text':comment}).success(function(data, status) {

        })
};

$scope.deleteComment = function(comment) {
           $http.delete('/api/v1/comments/'+ comment.id + '/');
           $scope.comments.splice($scope.comments.indexOf(comment), 1);
};
$scope.addComment = function(data){
  $http.post('/api/v1/comments/')
}


}]);

так вот не совсем понятно как отправить объект поста, подскажите пожалуйста. Фид как у инстаграма в версии для ПК (instagram.com)
Переписал post запрос, но все ровно не работает
:
$scope.postComment = function(comment, post) {
    var json = JSON.stringify({
        'comments_text':comment,
        'comments_post': post});
    alert(json);

      $http.post("/api/v1/comments/", json).success(function(data, status) {


      })
};


такая ошибка:
IntegrityError at /api/v1/comments/
null value in column "comments_post_id" violates not-null constraint
DETAIL: Failing row contains (124, asdfsafd, 1, 2016-05-27 21:48:01.332397+00, null).
  • Вопрос задан
  • 456 просмотров
Пригласить эксперта
Ответы на вопрос 1
DirecTwiX
@DirecTwiX
"display: flex;" уже предлагали?
Ну так пишет же, что в 'comments_post_id' должно быть число, а у тебя пусто.

Описание не очень понятно. Есть свой сайт, куда ты пытаешь коммент добавить?

Попробуй вот так:
var json = JSON.stringify({
        'comments_text':comment,
        'comments_post_id':1,
        'comments_post': post});

Или
post.comments_post_id = 1;
var json = JSON.stringify({
        'comments_text':comment,
        'comments_post': post});
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
29 мар. 2024, в 18:19
20000 руб./за проект
29 мар. 2024, в 18:08
2500 руб./за проект
29 мар. 2024, в 17:51
40000 руб./за проект