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!
You can have
likesin a many-to-many relationship while accessing this field anduser(as the owner of the post) field with FK related name:models.py
This way we can access
Postcreated by anUserwithuser.posts.all()and all posts liked by anUserwithuser.likes.all()views.py
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
requestobject.posts.html