mode
mode

Reputation: 123

I'd like to know if the ManyToMany Field for each post contains a user ID in django

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.

views.py

    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')

models.py

 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)

templates

    {% 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

Answers (1)

Kryštof Řeh&#225;ček
Kryštof Řeh&#225;ček

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

Related Questions