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 %}
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
– Marlon Baptista Quadros
With the
DEBUG=True
no more indicative of the error? Could you take the opportunity to understand how he is formatting the Urls– Leonardo Pessoa