......但它是!?我使用的是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
我没有使用表单,而是尝试在视图中创建对象:
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
答案 0 :(得分:3)
您应该为User
字段分配Comment.user
。您当前正在分配ID。你可以这样做:
comment = Comment(user=author, post=post, content=content)
或
comment = Comment(user_id=author_id, post=post, content=content)