......但它是!?我使用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
'author_id'不是'User' –