Django + AJAX - POST 404 (Not Found)

0

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

views.py

@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')

urls.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  %}
    
asked by anonymous 10.01.2018 / 15:07

1 answer

1

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

In JavaScript, try to store the #like button in 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  %}
    
05.02.2018 / 21:33