2016-03-04 35 views
2

......但它是!?我使用Django 1.9和Python 3无法指定'1':Comment.user必须是用户实例

我试图让一个帖子人评论,我的模型是这样的:

class Comment(models.Model): 
    user = models.ForeignKey(User, unique=False) 
    post = models.ForeignKey(Post, unique=False) 
    content = models.TextField(max_length=450) 
    created = models.DateField(auto_now=False,auto_now_add=True) 
    edited = models.BooleanField(default=False) 
    replies = models.ManyToManyField('Comment', blank=True) 
    score = models.BigIntegerField(default=0) 

    def __str__(self): 
     return self.content 

我使用的不是一个形式,而是我试图在视图中创建对象:

def PostView(request, user, slug): 
    instance = get_object_or_404(Post, user__username=user, slug=slug) 
    context = { 
     'object': instance, 
     'MEDIA_URL': MEDIA_URL, 
     'STATIC_URL': STATIC_URL 
    } 

    if request.method == 'POST': 

     data_type = request.POST.get('type') 

     if data_type == 'comment': 
      content = request.POST.get('content') 
      author = get_user(request) 
      author_id = author.id 
      post = instance 
      comment = Comment(user=author_id, post=post, content=content) 

但是这应该工作正常,但我在尝试后才能发表评论时,这真是奇怪的错误:

无法分配“1”:“Comment.user”必须是“用户”实例。

当我尝试创建对象时发生该错误。 Full traceback can be seen here

+1

'author_id'不是'User' –

回答

2

您应该为Comment.user字段指定User。您目前正在分配该ID。你可以这样做:

comment = Comment(user=author, post=post, content=content) 

comment = Comment(user_id=author_id, post=post, content=content) 
+0

哇,这真是奇怪。这是我尝试的第一件事,然后我得到了一个错误,但是当再次尝试时,它现在似乎神奇地工作。 Django必须像USB一样是第四维的。 –

相关问题