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')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…