Django - How to iterate over object that has a ManyToManyField with the User as the relational argument and get a specific User?

I have an art gallery web app that displays a grid of images. On each image are the number of users who have "liked" that image. I have already implemented dynamic liking/unliking with an int counter that increments/decrements the count in real time via AJAX.

What I am trying to do now that I can't figure out is:

1.) On page load, if the currently logged in user hasn't liked a specific image, display that specific image's like button in a certain color, say black. But if the currently logged in user has liked it, display the like button in a different color, say blue, to indicate which images this user has liked or not. Just like Facebook or Instagram.

Here is my Portrait model (with some fields omitted):

class Portrait(models.model):
    likes = models.ManyToManyField(User,related_name='like',default=None,blank=True)
    like_count = models.BigIntegerField(default=0)

Here is my views.py for the Portrait model:

def index(request):
    paintingObjects = Portrait.objects.all()
    context = {
        'paintingObjects': paintingObjects,
    }
    return render(request, "index.html", context)

Here is the portion of my index.html template I want to execute the check (pseudocode):

{% for paintingData in paintingObjects %}
    {% if request.user.is_authenticated %}
        {% if this current request.user is in this paintingData's 'likes' field %}
        <a role="button" class="like-click" id="{{paintingData.id}}">
            <span style="float: left;" class="p-1 mt-1">
                <i class="fa fa-thumbs-up" style="font-size:22px;color:blue"></i>
            </span>
        </a>
        {% else if the user hasn't liked this particular paintingData yet %}
        <a role="button" class="like-click" id="{{paintingData.id}}">
            <span style="float: left;" class="p-1 mt-1">
                <i class="fa fa-thumbs-up" style="font-size:22px;color:black"></i>
            </span>
        </a>
    {% endif %}
{% endfor %}

In my "likes" field of the Portrait model, how do I access the User(s) of each image and check if the currently logged in user is in the list?

You can access all the likes of an user by doing that :

request.user.like.all

Because User is the related object for the like attribute and the related_name is called "like".

Note that you should have done the opposite, your attribute should be singular "like" and the related_name plural "likes" because you access a set of like for a specific user

Back to Top