Search code examples
djangodjango-modelsdjango-templatesdjango-template-filters

Check either someone has liked a post or not within the template django


I have this model struture:

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    text = models.CharField(max_length=1200, blank=True)

class PostLike(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

Template

for post in posts
...
# want to check here, something like:
if post.userliked write something endif
...
endfor

Now what I want is to check either the current loggedin user has liked the post or not within the django template.

I have tried, post.postlike_set but of course that won't work because it's for all the likes, is there anyway that I can check if the current loggedin user has liked the post or not.

Please help!


Solution

  • You can have likes in a many-to-many relationship while accessing this field and user (as the owner of the post) field with FK related name:

    models.py

    class Post(models.Model):
        user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
        text = models.TextField()
        likes = models.ManyToManyField(User, related_name='likes')
    

    This way we can access Post created by an User with user.posts.all() and all posts liked by an User with user.likes.all()

    views.py

    def posts(request):
        posts = Post.objects.all()
        return render(request, 'posts.html', {'posts': posts})
    

    Since you want to check the logged in user, we do not need to pass it by context, instead we access it directly in template using the request object.

    posts.html

    {% extends 'base.html' %}
    
    {% block content %}
        {% for post in posts %}
        <p>{{post}}</p>
            {% if post in request.user.likes.all %}
                <p> You already liked this post </p>
            {% else %}
                <button>Like</button>
            {% endif %}
            <hr>
        {% endfor %}
    {% endblock content %}