Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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?
- class CompanyLikesAPIView(APIView):
- permission_classes = (permissions.IsAuthenticated, )
- def get(self, request, slug=None, format=None):
- company_instance = get_object_or_404(Company, slug=slug)
- company_like = company_instance.likes.all()
- user = request.user
- unlike = False
- liked = False
- if user.is_authenticated():
- if user in company_like:
- company_instance.likes.remove(user)
- unlike = True
- liked = False
- else:
- company_instance.likes.add(user)
- liked = True
- data = {
- 'unlike': unlike,
- 'liked': liked
- }
- return Response(data)
- <script>
- $(document).ready(function(){
- function updateText(btn, newCount, verb){
- btn.text(newCount + " " + verb)
- }
- $(".like-company").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")
- }
- }, error: function(error){
- console.log(error)
- }
- })
- }
- })
- })
- </script>
- <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