I , so I wrote an application with django and implemented a like and unlike function but I noticed that it works fine but the problem is if a user likes a post and decides to unlike it , the likes . count would go to -1 instead of 0 and thus it is possible for a two users like to become 3 but if one of the two unlikes it then it goes to 1 . below is my jQuery function jQuery
$(document).ready(function(){
function updateText(btn, newCount, verb){
btn.text(newCount + " " + verb)
}
$(".like-btn").click(function(e){
e.preventDefault()
var this_ = $(this)
var likeUrl = this_.attr("data-href")
var likeCount = parseInt(this_.attr("data-likes")) | 0
var addLike = likeCount + 1
var removeLike = likeCount - 1
if (likeUrl){
$.ajax({
url: likeUrl,
method: "GET",
data: {},
success: function(data){
console.log(data)
var newLikes;
if (data.liked){
updateText(this_, addLike, "Unlike")
} else {
updateText(this_, removeLike, "Like")
// remove one like
}
}, error: function(error){
console.log(error)
console.log("error")
}
})
}
})
})
view.html
<p><a class='like-btn' data-href='{{ obj.get_api_like_url }}' data-likes='{{ obj.likes.count }}' href='{{ obj.get_like_url }}'>{{ obj.likes.count }} Like</a></p>
View.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
class PostLikeAPIToggle(APIView):
authentication_classes = (authentication.SessionAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
def get(self, request, slug=None, format=None):
# slug = self.kwargs.get("slug")
obj = get_object_or_404(Post, slug=slug)
url_ = obj.get_absolute_url()
user = self.request.user
updated = False
liked = False
if user.is_authenticated():
if user in obj.likes.all():
liked = False
obj.likes.remove(user)
else:
liked = True
obj.likes.add(user)
updated = True
data = {
"updated": updated,
"liked": liked
}
return Response(data)
if any other part of my code is required I would gladly supply it. Thanks