-1

I implemented the post like feature using ajax in the Django project, but it doesn't work. And it gives a 404 error in the console. template.html

<script>
    $(document).ready(function(){
        $(".line-button").click(function(){
            var post_id = $(this).closest("post").data("post-id");
            var button = $(button);
        $.ajax({
            type: 'POST',
            url: 'like-post/',
            data: {'post_id': post_id, 'csrfmiddlewaretoken':'{{csrf_token}}'},
            
            success: function(data){
                if(data.liked){
                    button.text('unLike');
                }else{
                    button.text('Like');
                }
                $(".likes-count").text(data.post_likes_count);
            }
        })
            })
        })
</script>

views.py

@require_POST
def like_post(request):
    post_id = request.POST.get("post_id")
    post = get_object_or_404(Post, id=post_id)
    if request.user in post.likes.all():
        post.likes.remove(request.user)
        liked = False
    else:
        post.likes.add(request.user)
        liked = True
    post_likes_count = post.likes.count()

    response_data = {
        'liked': liked, 'post_likes_count': post_likes_count
    }
    return JsonResponse(response_data)

urls.py

path('like-post/', views.like_post, name="like_post"),
4
  • You're using relative paths, does the resulting URL being requested from the client match what the server expects? Commented Nov 17 at 18:49
  • Yes, I used the same path to execute the view. Commented Nov 17 at 19:09
  • What is the URL of the page you are on, when you are triggering this? Commented Nov 18 at 7:25
  • You need to do some basic debugging. You're getting a 404. You have get_object_or_404. Ensure you're getting the post_id and that you have a corresponding object. Commented Nov 18 at 15:30

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.