Shohanul Alam
Shohanul Alam

Reputation: 145

How to check if a user already likes a blog post or not in django

I want to set my like unlike button by verifying a query that the user already likes this post or not. If the user already likes this, the button will be "Unlike" and "Like" otherwise. I can not find the proper way to make the query and how to implement it in my template. Thanks in advance.

My model:

class Tweet(models.Model):
    added = models.DateTimeField(auto_now_add=True)
    tweeter = models.ForeignKey(UserProfile, related_name='user_tweets')
    content = models.TextField(max_length=140)
    likes = models.IntegerField(default=0)

    def __unicode__(self):
        return self.content

    def total_likes(self):
        return self.likes.count()

    def approved_comments(self):
        return self.comments.filter(approved_comment=True)

class Like(models.Model):
    liker = models.ForeignKey(UserProfile, related_name='liked_user')
    liked_tweet = models.ForeignKey('Tweet', related_name='liked_post')
    liked_date = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return u'%s liked %s tweet' % (self.liker, self.liked_tweet)

Upvotes: 2

Views: 1433

Answers (2)

MicroPyramid
MicroPyramid

Reputation: 1630

Just check for the record with user and tweet in Like table.

like_obj, created = Like.objects.get_or_create(liker=user, liked_tweet=tweet)
if created:
   # code for new user liked tweet
else:
   # code for record found with user and tweet so unlike tweet by like_obj.delete()

Upvotes: 1

Rajesh Yogeshwar
Rajesh Yogeshwar

Reputation: 2179

You can simply query Like model with the Tweet and UserProfile instance for which you are verifying. If a record exists then user has already liked that tweet.

Sample:

is_liked = False
try:
    Like.objects.get(liked_tweet=tweet, liker=user)
    is_liked = True
except Like.DoesNotExist:
    pass

Upvotes: 5

Related Questions