How do I affect a single looped element in Django html?

I'm building an app in Django, using Bulma for styling. I have a Polishes model that has a favorites field, which references the User (users can save polishes to their list of favorites):

models.py:

class Polish(models.Model):
    name = models.CharField(max_length=100)
    image = models.CharField(max_length=400, default="https://www.dictionary.com/e/wp-content/uploads/2018/02/nail-polish-light-skin-tone.png")
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name='polishes')
    favorites = models.ManyToManyField(User, related_name='favorite', default=None, blank=True)

    def __str__(self):
        return self.name

The add_favorites function checks to see if the polish has been added to the user's favorites already, and if it has, it removes the polish from the list. If it hasn't, it adds it:

views.py:

@ login_required
def add_favorite(request, id):
    polish = get_object_or_404(Polish, id=id)
    if polish.favorites.filter(id=request.user.id).exists():
        polish.favorites.remove(request.user.pk)
    else:
        polish.favorites.add(request.user.pk)
    return redirect('favorites_list')

When I render the list of polishes, I'm using Bulma cards, displaying one polish per card. In the footer of the card, I want it to say 'Save to Favorites' if the polish is not in the user's list of favoties and 'Remove from Favorites' if it is. I'm struggling to get this piece to work. It will currently show either Save to Favorites or Remove from Favorites on all of the cards.

Does anyone have any insight on how to render a different message only on those that are already on the favorites list?

polish_list.html:

...
<div class="gallery">
  {% for polish in polishes %}
  <a href="{% url 'polish_reviews' polish.pk %}">
    <div class="card">
      <div class="card-header">
        <p class="card-header-title">{{polish.name}} by {{polish.brand}}</p>
      </div>
      <div class="card-image">
        <figure class="image is-square">
          <img src="{{polish.image}}" alt="{{polish.name}}" />
        </figure>
      </div>
      <footer class="card-footer">
        {% if polish.favorites %}
        <a href="{% url 'add_favorite' polish.id%}" class="card-footer-item">Remove from Favorites</a>
        {% elif user.is_authenticated %}
        <a href="{% url 'add_favorite' polish.id%}" class="card-footer-item">Save to Favorites</a>
        {% else %}
        <a href="{% url 'login' %}" class="card-footer-item">Save to Favorites</a> 
        {%endif%}
      </footer>
    </div>
  </a>
  {% empty %}
  
  <article class="message">
    <div class="message-header">
      <p>No Polishes Available</p>
    </div>
  </article>
  {% endfor %}
</div>
...

I have tried using a conditional in my polish_list.html - {% if polish.favorites %} - but this will make the change on all of the cards rather than just on those that are saved to favorites.

Back to Top