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!
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')