为什么我在这里得到空值?

时间:2016-05-27 23:02:46

标签: javascript python angularjs django django-rest-framework

我使用角度如下的$ http.posts:

$scope.postComment = function(comment, post) {
    var json = JSON.stringify({
         'comments_post': post,
        'comments_text':comment});
    alert(json);

      $http.post("/api/v1/comments/", json).success(function(json, status) {
            $scope.comment = json;

      })
};

请求有效负载: enter image description here 我的json评论必须如下:

{
        "comments_text": "n km mn mn",
        "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 в 22:36",
                "is_superuser": true,
                "username": "alexandr",
                "first_name": "",
                "last_name": "",
                "email": "alexdomoryonok@gmail.com",
                "is_staff": true,
                "is_active": true,
                "date_joined": "2016-05-25 в 10:33",
                "groups": [],
                "user_permissions": []
            }
        },
        "posted": "2016-05-27 в 22:55",
        "comments_author": {
            "id": 1,
            "password": "pbkdf2_sha256$24000$kSUmB51QpUSi$yWJZJt539Mj7+TLGz1tS+uIMk9dHs766opPlw8FEX0E=",
            "last_login": "2016-05-27 в 22:36",
            "is_superuser": true,
            "username": "alexandr",
            "first_name": "",
            "last_name": "",
            "email": "alexdomoryonok@gmail.com",
            "is_staff": true,
            "is_active": true,
            "date_joined": "2016-05-25 в 10:33",
            "groups": [],
            "user_permissions": []
        },
        "id": 165
    }

但是我得到了django异常: enter image description here

我的模板:

<div ng-repeat="post in filteredPosts" ng-if="post.check">

                <div class="row">
                    <div class="col-sm-5 col-sm-offset-3">
                        <div class="thumbnail post">
                            <div class="caption">
                    <span ng-if="post.image">
                    <img ng-src="{{post.image}}" class="img-responsive" alt="">
                    </span>
                                <p>{{post.content| limitTo:200}}...</p>
                                <p>Aвтор: <a ng-href='/authsys/{{post.user.username}}/'>{{post.user.username}}</a></p>
                                <p>Создано: {{post.timestamp}}</p>
                                <p>Обновлено: {{post.updated}}</p>

                                <div class="btn btn-danger" ng-if="user.user == post.user.username" method="delete"
                                     ng-click="deletePost(post)">Удалить
                                </div>
                            </div>
                            <div ng-repeat="comment in comments" ng-if="comment.comments_post.id == post.id">
                                <div class="panel panel-default">
                     <span ng-if="user.user == comment.comments_author.username">
                                          <a href="" ng-click="deleteComment(comment)" style="margin-left: 95%"><i
                                                  class="glyphicon glyphicon-remove"></i></a>
                         </span>
                                    <div class="panel-body">
                                        {{comment.comments_text}}
                                    </div>
                                    <p style="margin-left: 85%"><a
                                            href="/authsys/{{comment.comments_author.username}}/">{{comment.comments_author.username}}</a>
                                    </p>

                                </div>
                            </div>

                            <input type="text" ng-model="text">
                            <input type="button" class="btn btn-default" value="Добавить" ng-click="postComment(text, post)">
                        </div>
                    </div>
                </div>
            </div>

models.py:

class Posts(models.Model):
    class Meta:
        verbose_name = 'Пост'
        verbose_name_plural = 'Посты'
        ordering = ['-timestamp', '-updated']

    title = models.CharField(max_length=120, verbose_name='Заголовок')
    image = models.ImageField(null=True, blank=True,
                              height_field='height_field',
                              width_field='width_field',
                              verbose_name='Изображение')
    height_field = models.IntegerField(default=0, null=True, verbose_name='высота')
    width_field = models.IntegerField(default=0, null=True, verbose_name='ширина')
    content = models.TextField(verbose_name='Текст')
    check = models.BooleanField(default=False, verbose_name='Одобрить')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)  # User
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    def __unicode__(self):
        return self.title

    def __str__(self):
        return self.title

    # for detail view
    def get_absolute_url(self):
        return "/posts/detail/{0}".format(self.id)

class Comments(models.Model):
    class Meta:
        db_table = 'comments'
        verbose_name = 'Комментарии'
        verbose_name_plural = 'Комментарии'

    comments_text = models.TextField(verbose_name='Ваш комментарий')
    posted = models.DateTimeField(auto_now_add=True)
    comments_author = models.ForeignKey(User, default=1)
    comments_post = models.ForeignKey(Posts)

............................................... .................................................. .............

1 个答案:

答案 0 :(得分:3)

基本上错误是什么,您的数据库在NOT NULL上有一个comments_post_id约束,并且您正在尝试向该列插入值为null的内容。

嗯,你的问题在这里:

$scope.postComment = function(comment, post) {
var json = JSON.stringify({
     'comments_post': post,
    'comments_text':comment});
alert(json);

  $http.post("/api/v1/comments/", json).success(function(json, status) {
        $scope.comment = json;

  })
};

您正在数据库中插入(至少发布到该路由以插入)只有几个参数,您的表需要comments_post_id值,它不能为空。我不知道你的表之间的关系如何,但你的comments_post_id myst有价值。或者您通过邮寄一个值,或者做其他事情。

// UPDATE

在查看代码后,您会在评论和帖子之间建立关系。我不知道它是如何与python一起工作的,但是,对于其他现代的mvc框架,你必须插入一个东西才能在关系的外键上使用这个主键。

例如。

您必须插入帖子,然后插入引用帖子的评论。我会做什么角度(伪算法)。

var post_id = 123;  // got from someplace
var json = JSON.stringify({
         'comments_post': post,
        'comments_text':comment,
        'comments_post_id' : post_id});

$http.post("/api/v1/comments/", json).success(function(json, status) {
            $scope.comment = json;

      })