显示喜欢django上的帖子的用户

好吧,我的项目功能之一就是为帖子提供喜欢,并且完成后,喜欢该帖子的用户可能会出现在“喜欢”计数旁边,问题是用户由于某种原因没有出现。我认为模型中存在错误,我认为应该有一个定义可以显示用户或类似的东西。

views.py

    def like_post(request):
        user = request.user
        if request.method == 'POST':
          post_id = request.POST.get('post_id')
          post_obj = Post.objects.get(id=post_id)
          if user in post_obj.liked.all():
            post_obj.liked.remove(user)
          else:
            post_obj.liked.add(user)
          like, created = Like.objects.get_or_create(author=user, post_id=post_id)
          if not created:
            if like.value == 'Like':
              like.value == 'Unlike'
            else:
              like.value = 'Like'

          like.save()
        return redirect('imagelist')

    def imagelist(request):
        images = Post.objects.all()
        context2 = {
            "images": images,
        }
        return render(request, 'imagelist.html', context2)

型号

    class Like(models.Model):
        author = models.ForeignKey(User, on_delete=models.CASCADE)
        post = models.ForeignKey(Post, on_delete=models.CASCADE)
        value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10)

        def __str__(self):
            return str(self.post)

    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)

        @property
        def num_likes(self):
            return self.liked.all().count()

imagelist.html

    <strong>{{ image.liked.user }}</strong>
评论
  • 海绵宝宝
    海绵宝宝 回复

    您必须像这样使用循环:

    {% for user in image.liked.all %}
     {{ user.username }}
    {% endfor %}