Reputation: 123
I'm trying to make a blog web.
I want to change the color of the 'like it button' like Instagram depending on whether users like it or not.
But I don't know how to build this.
def list(self, request, *args, **kwargs):
user = request.user
if not user.is_authenticated:
return redirect('blog:signup')
else:
response = Blog.objects.filter(owner=user.id)
return Response({'posts': response, 'user': user}, template_name='blog/blog_list.html')
class Blog(models.Model):
title = models.CharField(max_length=255)
body = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
likes = models.ManyToManyField(User, related_name='likes', blank=True, default='')
owner = models.ForeignKey(User, on_delete=models.CASCADE)
{% for post in posts %}
<button type="button" class="like" name="{{ post.pk }}" >
{% if post.likes.exist %}
<img class="float-left card-icon mx-1 like-img" src="{% static 'blog/like.png' %}" alt="">
{% else %}
<img class="float-left card-icon mx-1 like-img" src="{% static 'blog/favorite.png' %}" alt="">
{% endif %}
</button>
I'm trying to filter in the template. but post.likes.exists is not what I want.
This code below is what I want.
x = user.likes.through.objects.filter(blog=obj.id, user__id=user.id).exists()
Can I implement this code as a template code?
Or is there another solution to this?
Thank you!
Upvotes: 0
Views: 49
Reputation: 2483
Sure, one solution to this would be implementing this as a template tag which will receive this arguments and return boolean as a result.
@register.filter
def likes_post(user, post):
return user.likes.filter(blog=blog).exists()
And then use it in the template like
{% for post in posts %}
<button type="button" class="like" name="{{ post.pk }}" >
{% if user|likes_post:post %}
<img class="float-left card-icon mx-1 like-img" src="{% static 'blog/like.png' %}" alt="">
{% else %}
<img class="float-left card-icon mx-1 like-img" src="{% static 'blog/favorite.png' %}" alt="">
{% endif %}
</button>
{% endfor %}
Do not forget to add the tag in the tmeplatetags directory. Read the Django docs.
Upvotes: 1