How to fix Not Found: /blogs/like when adding Ajax to like button

Submitted 3 years, 5 months ago
Ticket #291
Views 254
Language/Framework Javascript
Priority Medium
Status Closed

I am trying to make the like button in the post_detail.html page clicked without refreshing the page so, I included the like section in a separate HTML called like-section.html. The problem is now I am getting a: Not Found: /blogs/like

when I click on the like button and it doesn't change anything when I click it except in the terminal I see this error Not Found: /blogs/like

How do I solve this error and what am I missing

Here is the model.py:

class Post(models.Model):
    ------------------------------
    liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked')

Here is the views.py:

def like_post(request):
    user = request.user
    post_obj = None

    if request.method == 'POST':
        post_id = request.POST.get('post_id')

        try:
            post_obj = Post.objects.get(id=post_id)
        except Post.DoesNotExist:
            return JsonResponse({'detail': 'Not found'}, status=404)
        else:
            if user in post_obj.liked.all():
                post_obj.liked.remove(user)
            else:
                post_obj.liked.add(user)

            like, created = Like.objects.get_or_create(user=user, post_id=post_id)
            if not created:
                if like.value == 'Like':
                    like.value = 'Unlike'
            else:
                like.value = 'Like'
            like.save()
            context = {
                'post_id': post_id,
            }
            if request.is_ajax:
                html = render_to_string('blog/like_section.html', context,
                                        request=request)
                return JsonResponse({'form': html})
            elif request.method == 'GET':
                post_id = request.GET.get('post_id')
                try:
                    post_obj = Post.objects.get(id=post_id)
                except Post.DoesNotExist:
                    return JsonResponse({'detail': 'Not found'}, status=404)

Here is the like-s;:ection.html:

          <form action="{% url 'blog:like-post' %}" method="POST" class="like-form" id="{{post.id}}">
            {% csrf_token %}
            <input type="hidden" name="post_id" value='{{post.id}}'>

            {% if user not in post.liked.all %}
              <a id="like" class="bwhite sm-button" style="color: grey; background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none;">
                <i class="far fa-thumbs-up" type="submit"></i>
              </a>
            {% else %}
              <a id="like" class="bwhite sm-button" style="color: blue;background-color: Transparent; background-repeat:no-repeat; border: none; cursor:pointer; overflow: hidden; outline:none;" >
                <i class="far fa-thumbs-up" type="submit"></i>
              </a>
            {% endif %}
            <div class="like-count{{post.id}}">{{ post.num_likes }} Likes</div>
          </form>

Here is the script:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script>
        $( document ).ready(function() {
            let display = false
            $(".cmt_btn").click(function () {
                if (display===false) {
                    $(this).next(".comment-box").show("fast");
                    display=true
                } else {
                    $(this).next(".comment-box").hide("fast");
                    display=false
                }
            });
        });
  </script>
<script>
        $(document).on('click', '#like', function(event){
          event.preventDefault();
          var pk = $(this).attr('value');
          $.ajax({
            type: 'POST',
            url: '{% url "blog:like-post" %}',
            data: {'post_id':pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
            dataType: 'json',
            success: function(response){
              $('#like-section').html(response['form'])
              console.log($('#like-section').html(response['form']));
            },
            error: function(rs, e){
              console.log(rs.responseText);
            },
          });
        });
  </script>

here is the urls.py

    path('blog/<slug:slug>/', PostDetailView.as_view(), name='post-detail'),
    path('blogs/like', like_post, name='like-post'),

Submitted on Nov 15, 20

in your js file, can you try console.log(url) and check what URL its returning? - Vengat 3 years, 5 months ago

{"detail": "Not found"} - ahmed.hisham87 3 years, 5 months ago

then your POST url is not working. - Vengat 3 years, 5 months ago
add a comment

1 Answer

Verified

I usually prefer to read the URL from the form itself.,

<script type="text/javascript">
    var frm = $('#FORM-ID');
    frm.submit(function () {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                $("#somedata").html(data);
            },
            error: function(data) {
                $("#someid").html("error!");
            }
        });
        return false;
    });
</script>

Submitted 3 years, 5 months ago

Thank you, could you just add some explanation as I am new to javascript and ajax, I am trying to understand the cycle to implement it.

- ahmed.hisham87 3 years, 5 months ago

basically you have to use input hidden value method or read the form action url in Javascript to grab the URL. if you still have doubt then let me know, we can connect and discuss.

- Vengat 3 years, 5 months ago

can you update the status of this ticket?

- Vengat 3 years, 5 months ago


Latest Blogs