404 not found error Django URL with JavaScript fetch function
I'm building a Todo app with Django and JavaScript. I've reached the point where when I click a "trash" button, the note should be deleted, but it shows an error in the console, the reason for which is not clear to me, since I specified the correct URL path. The error is appears when I click the "trash" button.
urlpatterns = [
path('', views.index, name="index"),
path('add_note/', views.add_note, name="add_note"),
path('del_note/<int:id>/', views.del_note, name="del_note"),
]
Django view function for deleting a note is also created.
@require_POST
def del_note(request, id):
del_obj = get_object_or_404(Note, id=id, user=request.user)
del_obj.delete()
return JsonResponse({"status": 200, "message": "Note deleted"})
And here is the HTML of the list with that "trash" button.
<ul class="todo__list">
{% for note in notes %}
<li class="todo__note flex" data-id="{{ note.id }}">
<div>
<input type="checkbox" />
<span>{{ note.text }}</span>
</div>
<div class="delete__edit">
<button class="edit-btn" id="editBtn" type="button">
<img src="{% static 'images/edit.svg' %}" alt="" />
</button>
<button class="delete-btn" id="deleteBtn" type="button">
<img src="{% static 'images/delete.svg' %}" alt="" />
</button>
</div>
</li>
{% endfor %}
</ul>
And this is JS fetch function for send request to django urls "del_note" path.
const noteList = document.querySelector(".todo__list");
//const delUrl = document.body.dataset.delNoteUrl;
function getCSRFToken() {
const tokenInput = document.querySelector("input[name='csrfmiddlewaretoken']");
return tokenInput ? tokenInput.value : "";
}
noteList.addEventListener("click", (e) => {
const deleteBtn = e.target.closest(".delete-btn");
// if (!deleteBtn) return;
const parentLi = deleteBtn.closest(".todo__note");
const noteId = parentLi.getAttribute("data-id");
console.log("Note id:", noteId); // 2 for example
fetch(`/del_note/${noteId}/`, {
method: "POST",
headers: {
"X-CSRFToken": getCSRFToken(),
},
})
.then((res) => {
if (!res.ok) {
throw new Error(`HTTP error ${res.status}`);
}
return res.json();
})
.then((data) => {
if (data.status === 200) {
parentLi.remove();
} else {
alert("Fail to delete the note.");
}
})
.catch((err) => {
console.error("Error:", err);
});
});
Error img is here.