Django + AJAX - POST 404 (Not Found)

Asked

Viewed 507 times

0

I am trying to implement a Likes system in a Django + AJAX application but when trying to do the operation in question I am getting the following error in the browser console: POST http://localhost:8000/forum/like/ 404 (Not Found). I don’t know what’s going on, can anyone help? Follow parts of my code below:

py views.

@require_POST 
def toggle_like(request):
    if request.method == "POST":
        user = request.user
        slug = request.POST.get('slug', None)
        question = get_object_or_404(Question, slug=slug)

        if question.likes.filter(id=user.id).exists():
            question.likes.remove(user)
        else:
            question.likes.add(user)
    
    context = {'likes-count': question.likes.count}

    return HttpResponse(json.dump(context), content_type='application/json')

py.

from django.urls import path

from . import views


app_name = 'forum'

urlpatterns = [
    path('like/', views.toggle_like, name='toggle-like'),
]

Question.html

{% block javascript %}
    <script>
        $('#like').click(() => {
            $.ajax({
                method: 'POST',
                url: "{% url 'forum:toggle-like' %}",
                data: {
                    'slug': $(this).attr('name'),
                    'csrfmiddlewaretoken': '{{ csrf_token }}'
                },
                dataType: 'json',
                success: (response) => {
                    alert(response.message);
                },
                error: (response, error) => {
                     alert(response.responseText);
                }
            })
        })
    </script>
{% endblock  %}

{% block content %}
    <p>Likes: {{ question.likes.count }} <input type="button" id="like" name="{{ question.slug }}" value="Like" /></p>
{% endblock  %}
  • 1

    How do you post the bug traceback and what version of Python and Django are you using? Just watching your code has a few points where the error might be happening. py views. Slug = request.POST.get('Slug', None) Question = get_object_or_404(Question, Slug=Slug) The 404 can happen that the 'Slug' parameter is not being passed correctly in the POST, tries to put a print(Slug) before the get_object_or_404. py.url And how is your root urls.py file? The problem may be on it. With more information I can help you better. Hug

  • With the DEBUG=True no more indicative of the error? Could you take the opportunity to understand how he is formatting the Urls

1 answer

1


I believe it is a scope problem in Javascript. When you access $(this).attr('name'), the $(this) is referring to the method ajax and not to the element with ID #like. So what’s going on is that $(this).attr('name') is returning undefined or an empty string. This value in turn is being used as a parameter in the search get_object_or_404, returning Http404.

In Javascript, try to store the button #like into a variable and then access it to compose the POST data.

{% block javascript %}
    <script>
        $('#like').click(() => {
            likeButton = $(this)
            $.ajax({
                method: 'POST',
                url: "{% url 'forum:toggle-like' %}",
                data: {
                    'slug': likeButton.attr('name'),
                    'csrfmiddlewaretoken': '{{ csrf_token }}'
                },
                dataType: 'json',
                success: (response) => {
                    alert(response.message);
                },
                error: (response, error) => {
                     alert(response.responseText);
                }
            })
        })
    </script>
{% endblock  %}

{% block content %}
    <p>Likes: {{ question.likes.count }} <input type="button" id="like" name="{{ question.slug }}" value="Like" /></p>
{% endblock  %}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.