-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"),
asked yesterday
4
  • You're using relative paths, does the resulting URL being requested from the client match what the server expects? Commented yesterday
  • Yes, I used the same path to execute the view. Commented yesterday
  • What is the URL of the page you are on, when you are triggering this? Commented 12 hours ago
  • 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 4 hours ago

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.