Reputation:
I want to allow an user to be able to like an post only once. Here is my code so far:
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.PositiveIntegerField(default=0)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
In views.py:
def LikePostView(request, pk):
post = get_object_or_404(Post, pk=pk)
post.likes = post.likes+1
post.save()
return render(request, 'blog/like_done.html')
Code to like a post on frontend:
<p class="content">{{ post.likes }} likes</p>
{% if user.is_authenticated %}
<a href='{% url "like_post" post.id %}'><i class="fa fa-thumbs-up" style="font-size:36px"></i></a>
{% else %}
<a onclick="alert('In order to like a post, you must be logged in!')" href='{% url "blog-home" %}'><i class="fa fa-thumbs-up" style="font-size:36px"></i></a>
{% endif %}
And like_done.html:
{% extends "blog/base.html" %}
{% block content %}
<h2 class="alert alert-success">Post Liked Successfuly!</h2>
<br>
<a class="btn btn-success" href="{% url 'blog-home' %}">Go Back Home?</a>
<br>
{% endblock content %}
So with all this, how would I make the user be allowed to only like a post once. I am only beginner, so please explain a little.
Upvotes: 0
Views: 166
Reputation: 695
If I get your question right, You want a user to be able to like a post once, and when the user clicks on the like button the second time it should 'unlike' right?
If so, this is what you should do:
In you Post model, the like should be like this likes = models.ManyToManyField(User, related_name='user_likes')
, a ManyToManyField
.
Then in your views:
def LikePostView(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.user in post.likes.all():
post.likes.remove(request.user)
else:
post.likes.add(request.user)
return render(request, 'blog/like_done.html')
This way if the user clicks the like button he will be added to the likes Field
and if he clicks it again he will be removed seems he is already there. So the user won't be able to like a post more than once.
Upvotes: 1