Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

python - How to add likes to my blog posts using generic relationships in Django

I'm trying to add a like/dislike functionality in Django using generic relationships. Can someone help me?

My post model



class Post(models.Model):
    title = models.CharField(max_length=225)
    post_image = models.ImageField(null=True, blank=True,  upload_to="images/")
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    post_date = models.DateTimeField(auto_now_add=True)
    
    
    def __str__(self):
        return self.title + ' | '  + str(self.author)

    class Meta:
        ordering = ['-post_date',]

    def get_absolute_url(self):
        return reverse('post-detail', args=(str(self.id)),)

Thanks in advance!

question from:https://stackoverflow.com/questions/65907599/how-to-add-likes-to-my-blog-posts-using-generic-relationships-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create a new class like below:

class LikedPost(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    liked_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.post.title + " liked by " + self.user.username

Then, whenever a user hit like button, do create a new LikedPost if not exist a user liking that post for like function, else remove that LikedPost for dislike function.

@login_required
def hit_like_button(request, pk):
    # Get the id of post
    post = get_object_or_404(Post, pk=pk)

    # Create a new LikedPost if this post is not liked by this user.
    liked_post, created = LikedPost.objects.get_or_create(
        post=post,
        user=request.user
    )
    # If not created new LikedPost <=> exist LikedPost = dislike.
    if not created:  #If get_or_create() function not created a new LikedPost
        liked_post.delete()
        messages.info(request, "This post was disliked.")
    else: # If created a new LikedPost => this user did not like this post 
        liked_post.save()
        messages.info(request, "This post was liked.")
    return redirect('home')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...