I am facing an issue with the 'live' like/unlike button functionality in Django and JavaScript DOM
Upon clicking the button, an error is triggered
POST http://127.0.0.1:8000/like/24 404 (Not Found)
likePost @ javascripts.js:24
(anonymous) @ javascripts.js:40
javascripts.js:7
I am unsure whether the problem lies within the 'await fetch' function or if I have incorrectly used a class or id somewhere. Where should I begin troubleshooting?
javascript.js
const reloadPostHTML = async (postId) => {
const homePageResponse = await fetch(window.location.href);
const newHTML = await homePageResponse.text();
const newDocument = new DOMParser().parseFromString(newHTML, "text/html");
console.log(newDocument)
const newPostElem = newDocument
.querySelector(`[data-post-id='${postId}']`)
.closest(".post");
const oldPostElem = document
.querySelector(`[data-post-id='${postId}']`)
.closest(".post");
oldPostElem.innerHTML = newPostElem.innerHTML;
makeLikeButton(oldPostElem.querySelector(".like-button-wrapper"));
};
const likePost = async (postId, csrfToken) => {
await fetch(`/like/${postId}`, {
method: 'POST',
credentials: 'include',
headers: {
"X-CSRFToken": csrfToken
}
});
reloadPostHTML(postId);
};
const makeLikeButton = (elem) => {
elem.querySelector('button').addEventListener("click", (event) => {
event.preventDefault();
const postId = elem.dataset.postId;
const csrfToken = elem.dataset.csrfToken;
likePost(postId, csrfToken);
});
};
const makeLikeButtons = () => {
for (let elem of document.getElementsByClassName("like-button-wrapper")) {
makeLikeButton(elem);
}
};
makeLikeButtons();
urls.py
path(
'article_detail/<int:pk>/',
login_required(
ArticleDetail.as_view(template_name = "web/article_detail_view.html")
),
name='article_detail'
),
path('like/<int:pk>', views.like, name='like'),
In the views, should I also check "if request.method == "POST":" ? views.py
def like(request, pk):
article = get_object_or_404(Article, id=request.POST.get("article_id"))
if article.likes.filter(id=request.user.id).exists():
article.likes.remove(request.user)
liked = False
else:
article.likes.add(request.user)
liked = True
return HttpResponseRedirect(reverse("article_detail", args=[int(pk)]))
and detail_view.py
class .post is included in the structure, hence I have used .closest(".post") in javascript.js
<div class="card post"> ........
<div class="like-button-wrapper"
data-post-id='{{ article.pk }}'
data-csrf-token='{{ csrf_token }}'>
{% if liked %}
<button class="btn btn-danger position-relative" type="submit" id="like" name="article_id"
value="{{article.id}}">
<i class="bi bi-hand-thumbs-down">
</i>
</button>
{% else %}
<button class="btn btn-primary position-relative" type="submit" id="like" name="article_id"
value="{{article.id}}">
<i class="bi bi-hand-thumbs-up">
</i>
<span
class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
{{ likes }}
</span>
</button>
{% endif %}
</div>