2016-03-04 45 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一樣是第四維的。 –

相關問題