Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1. #Issue is at start each company will have 0 like so when clicked on the like button, it shows 1 Unlike and if again clicked it will show -1 Like. When refresh it will show the right count with right verb. How do I fix this?
  2.  
  3. class CompanyLikesAPIView(APIView):
  4.     permission_classes = (permissions.IsAuthenticated, )
  5.  
  6.     def get(self, request, slug=None, format=None):
  7.         company_instance = get_object_or_404(Company, slug=slug)
  8.         company_like = company_instance.likes.all()
  9.         user = request.user
  10.         unlike = False
  11.         liked = False
  12.         if user.is_authenticated():
  13.             if user in company_like:
  14.                 company_instance.likes.remove(user)
  15.                 unlike = True
  16.                 liked = False
  17.             else:
  18.                 company_instance.likes.add(user)
  19.                 liked = True
  20.         data = {
  21.             'unlike': unlike,
  22.             'liked': liked
  23.         }
  24.         return Response(data)
  25.  
  26.  
  27. <script>
  28.         $(document).ready(function(){
  29.           function updateText(btn, newCount, verb){
  30.             btn.text(newCount + " " + verb)
  31.         }
  32.         $(".like-company").click(function(e){
  33.           e.preventDefault()
  34.           var this_ = $(this)
  35.           var likeUrl = this_.attr("data-href")
  36.           var likeCount = parseInt(this_.attr("data-likes")) || 0
  37.           var addLike = likeCount + 1
  38.           var removeLike = likeCount - 1
  39.           if (likeUrl){
  40.           $.ajax({
  41.             url: likeUrl,
  42.             method: "GET",
  43.             data: {},
  44.             success: function(data){
  45.               console.log(data)
  46.               var newLikes;
  47.               if (data.liked){
  48.                 updateText(this_, addLike, "Unlike")
  49.               } else {
  50.                 updateText(this_, removeLike, "Like")
  51.               }
  52.               }, error: function(error){
  53.                   console.log(error)
  54.                 }
  55.             })
  56.           }
  57.         })
  58.         })
  59. </script>
  60.  
  61. <a href="{{ company.get_like_url }}" class="btn btn-link like-company" data-href="{{ company.get_like_url }}" data-likes="{{ company.likes.count }}"><i class="fa fa-thumbs-o-up"></i>{{ company.likes.count }} like</a>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement