【发布时间】:2020-05-19 20:06:20
【问题描述】:
我正在尝试向我的项目添加评论系统,所有代码看起来都很好,但我收到此错误“ValueError at / 精确查找的 QuerySet 值必须限制为使用切片的一个结果”。我不知道出了什么问题,但错误可能在 views.py 文件上。
views.py
def imagelist(request):
images = Post.objects.all()
post = get_object_or_404(Post)
comments = Comment.objects.filter(post=images)
if request.method == 'POST':
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
contentt = request.POST.get('content')
comment = Comment.objects.create(post=images, user=request.user, content=content)
comment.save()
return HttpResponseRedirect(post.get_absolute_url())
else:
comment_form = CommentForm()
context2 = {
"images": images,
"comments": comments,
"comment_form": comment_form,
}
return render(request, 'imagelist.html', context2)
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField(max_length=160)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '{}-{}'.format(self.post.title.str(self.user.username))
class Post(models.Model):
text = models.CharField(max_length=200)
posti = models.ImageField(upload_to='media/images', null=True, blank="True")
video = models.FileField(upload_to='media/images', null=True, blank="True")
user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username')
liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')
updated = models.DateTimeField(auto_now=True)
created =models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.tittle)
forms.py
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('content',)
【问题讨论】:
-
你能分享完整的回溯吗?
-
同样
__str__方法不对,把format方法参数改成self.post.title, str(self.user.username) -
这个视图有点奇怪,你列出了所有
Post对象,但是当你发出POST请求来创建新评论时,你的视图不知道Post你是什么发表评论。 -
@DenizKaplan 在模型上修复了该问题并没有改变任何东西,您能否更好地向我解释一下我可以在视图上做什么或发布答案?
-
我猜stackoverflow.com/a/61900155/2474573 这就是答案,如果您无法实现您的目标,请尝试使用您的回溯更新您的问题。
标签: python django django-models django-forms django-views