[英]django with ajax like and unlike
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 . 我,所以我用django编写了一个应用程序,并实现了like和different函数,但我注意到它可以正常工作,但问题是用户是否喜欢某个帖子并决定不喜欢,喜欢。 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 .
count将变为-1而不是0,因此两个用户有可能变成3,但是如果两个用户之一不同,则它变为1。 below is my jQuery function jQuery
以下是我的jQuery函数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 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 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
谢谢
You haven't updated the data-likes
when the user has liked or unliked a post. 用户喜欢或不喜欢帖子时,您尚未更新
data-likes
。 Since, the page won't refresh the tag containing attribute data-likes
with value {{ obj.likes.count }}
will never re-render on UI. 由于此页面不会刷新包含值为
{{ obj.likes.count }}
属性data-likes
的标签,因此永远不会在UI上重新呈现。
if (data.liked) {
// ...
} else {
// ...
}
// update the `data-likes`
this_.data('likes', likeCount);
Note : You can use .data()
method to access the data-* attributes, rather than using attr
. 注意 :可以使用
.data()
方法访问data- *属性,而不是使用attr
。
Ref: jQuery .data() docs 参考: jQuery .data()文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.