1👍
✅
You can try the following way:
view.py
@login_required
def BlogLike(request, slug):
post = get_object_or_404(BlogPost, slug=slug)
liked = False
if request.method == 'POST':
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
liked = False
else:
post.likes.add(request.user)
liked = True
return HttpResponseRedirect(reverse('viewblog', args=[post.slug]))
and in html
{% csrf_token %}
<form action="{% url 'likepost' post.slug %}" method="POST">
<button type="submit" id="like" value="{{ post.slug }}" class="btn btn-outline-secondary rounded-0 custom-button">
{% if post.likes.filter(id=request.user.id).exists %}
Unlike <i class="fa-solid fa-heart-crack"></i>
{% else %}
Like <i class="fa-solid fa-heart"></i>
{% endif %}
</button>
</form>
Source:stackexchange.com