首页 > 解决方案 > 如何在 django 上添加评论

问题描述

我正在尝试向我的项目添加评论系统,所有代码看起来都很好,但我收到此错误“ValueError at / The QuerySet value for an exact lookup must be limited to one result using slicing”。我不知道出了什么问题,但错误可能在 views.py 文件上。

视图.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)

模型.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)

表格.py

    class CommentForm(forms.ModelForm):
        class Meta:
            model = Comment
            fields = ('content',)

标签: pythondjangodjango-modelsdjango-formsdjango-views

解决方案


您需要将create单个注释传递给注释的方法,Post因为相应的字段是 aForeignKey并且您正在传递整个查询集 ( Post.objects.all())

您只需要获得评论应该存在的帖子。

single_post = Post.objects.get(pk=the_post_pk)
comment = Comment.objects.create(post=single_post, user=request.user, content=content)

推荐阅读