简体   繁体   中英

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 . 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM