django与ajax喜欢和不同

时间:2023-01-19 16:16:53

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

我,所以我用django编写了一个应用程序并实现了一个类似和不同的功能,但我注意到它工作正常,但问题是如果用户喜欢一个帖子并决定不喜欢它,喜欢。 count将变为-1而不是0,因此两个用户可能会变为3,但如果两个用户中的一个不喜欢它,那么它将变为1。下面是我的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

<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

如果需要我的代码的任何其他部分,我很乐意提供它。谢谢

1 个解决方案

#1


0  

You haven't updated the data-likes when the user has liked or unliked a post. 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}}将永远不会在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.
Ref: jQuery .data() docs

注意:您可以使用.data()方法访问data- *属性,而不是使用attr。参考:jQuery .data()docs

#1


0  

You haven't updated the data-likes when the user has liked or unliked a post. 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}}将永远不会在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.
Ref: jQuery .data() docs

注意:您可以使用.data()方法访问data- *属性,而不是使用attr。参考:jQuery .data()docs