django 更改喜欢按钮颜色时的帖子

0lvr5msh  于 2023-05-08  发布在  Go
关注(0)|答案(1)|浏览(110)

我有这个社交媒体应用程序,我想当用户喜欢后的颜色是红色的,如果不是它是黑色的。以下是我的观点:

@login_required()
def likes(request, post_id):
    user = request.user
    post = Post.objects.get(id=post_id)
    current_likes = post.likes

    liked = Likes.objects.filter(user=user, post=post).count()
    if not liked:
        liked = Likes.objects.create(user=user, post=post)
        current_likes = current_likes + 1

    else:
        liked = Likes.objects.filter(user=user, post=post).delete()
        current_likes = current_likes - 1

    post.likes = current_likes
    post.save()
    return HttpResponseRedirect(reverse('post_detail', args=[post_id]))

我的post-detail.html页面和index.html看起来像:

<a href="{% url 'like' post.id %}" class="post__button">
    {% if post.likes %}
        <i class="fa fa-heart" style="color: red; font-size: 27px;"></i>
    {% else %}
         <i class="fa-regular fa-heart" style="color: black; font-size: 27px;"></i>
    {% endif %}
 </a>

但是如果帖子有任何喜欢的话,即使不是来自当前用户,也可以说“if post.likes”,并使喜欢按钮变红,如果帖子有0个喜欢,则为黑色。但我希望它与当前登录的用户(user=request.user)一样
我已经尝试了以下在html无济于事

if user.post.likes
if request.user.post.likes
if not liked
if liked

urls.py

path('<uuid:post_id>/like', views.likes, name="like"),

model.py

class Likes(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_likes")
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post_likes")
jexiocij

jexiocij1#

我是怎么做到的呢?我在Post模型中使用了一个manytomany字段。likes = models.ManyToManyField(User, related_name='blog_posts')我还在模型中添加了一个名为total_likes()的函数。

def total_likes(self):
        return self.likes.count()

然后我创建一个视图,用于在列表中添加和删除用户。

@login_required
def LikeView(request, pk):
    post = get_object_or_404(Post, id=request.POST.get('post_id'))
    if post.likes.filter(id=request.user.id).exists():
        post.likes.remove(request.user)
    else:
        post.likes.add(request.user)
    return HttpResponseRedirect(reverse('post-detail', args=[str(pk)]))

然后在我看来,我创建了一个喜欢的变量。

stuff = get_object_or_404(Post, id=pk)
total_likes = stuff.total_likes()
liked = False
if stuff.likes.filter(id=request.user.id).exists():
    liked = True

然后我在模板中使用一点逻辑来显示两个不同的按钮。

{% if user.username == post.author.username %}
<h5>You cannot vote on your own post!</h5>
{% else %}
<form action="{% url 'like_post' post.pk %}" method="POST">
    {% csrf_token %}{% if liked %}
    <button type="submit" name="post_id" value="{{ post.id }}" class="btn btn-warning btn-sm">Unlike</button> -
    {{ total_likes }} Like/s
    {% else %}
    <button type="submit" name="post_id" value="{{ post.id }}" class="btn btn-outline-primary btn-sm">Like</button>
    -
    {{ total_likes }} Like/s
    {% endif %}
</form>
  
{% endif %}
  • 我希望这对你有帮助!*

相关问题