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

时间:2020-05-18 01:41:49

标签: python html django django-models django-views

好吧,我的专案功能之一就是为喜欢的帖子提供喜欢,当完成之后,喜欢该帖子的用户可能会出现在喜欢计数旁边,问题是用户没有出现一些理由。我认为模型中存在错误,我认为应该有一个定义可以向用户显示或类似内容。

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)

Models.py

    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>

1 个答案:

答案 0 :(得分:0)

您必须像这样使用循环:

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