gpt4 book ai didi

django - 无法分配 '1' : Comment. 用户必须是用户实例

转载 作者:行者123 更新时间:2023-12-04 15:32:35 25 4
gpt4 key购买 nike

... 但它是!?我正在使用 Django 1.9 和 Python 3。

我试图让人们对帖子发表评论,我的模型如下所示:

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

我没有使用表单,而是尝试在 View 中创建对象:
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)

但是,这应该可以正常工作,但是在尝试发布评论时出现了这个非常奇怪的错误:

Cannot assign "1": "Comment.user" must be a "User" instance.



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

最佳答案

您应该分配一个 UserComment.user field 。您当前正在分配 ID。你可以这样做:

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

或者
comment = Comment(user_id=author_id, post=post, content=content)

关于django - 无法分配 '1' : Comment. 用户必须是用户实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35801797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com