CS50W - Network - Like Button working but Like count is not updating
I am currently working on Project4 from CS50W. The task is to write a social media like site where users can post, follow and like.
I have implemented a like button to every post (which is wokring fine) unfortunately I have to refresh the page for the like to show. I whould rather want the like to update directly after clicking the like button.
I am creating the div for the posts via Javascript and calling the like_post function onclick
function load_posts() {
// get posts from /posts API Route
fetch('/all_posts')
.then(response => response.json())
.then(posts => {
// create a div element for each post
posts.forEach(post => {
let div = document.createElement('div');
div.className = "card post-card";
div.innerHTML = `
<div class="card-body">
<h5 class="card-title">${post['username']}</h5>
<h6 class="card-subtitle mb-2 text-muted">${post['timestamp']}</h6>
<p class="card-text">${post['text']}</p>
<button class="card-text like-button" onclick="like_post(${post.id});"><h3> ♥ </button> </h3>
${post['likes']}
</div>
`;
// append div to posts-view
document.querySelector('#posts-view').append(div);
});
});
}
function like_post(post_id) {
fetch('/post/' + post_id, {
method: 'PUT',
body: JSON.stringify({
like: true
})
});
}
this is my view funtion to handle most post related requests
@csrf_exempt
@login_required
def post(request, post_id):
# Query for requested post
try:
post = Post.objects.get(pk=post_id)
user = User.objects.get(username=request.user)
except Post.DoesNotExist:
return JsonResponse({"error": "Post not found."}, status=404)
# Return post contents
if request.method == "GET":
return JsonResponse(post.serialize())
# Update likes
elif request.method == "PUT":
data = json.loads(request.body)
if data.get("like") is not None and data.get("like") is True:
if post.likes.filter(username=user.username).exists():
post.likes.remove(User.objects.get(username=user.username))
else:
post.likes.add(User.objects.get(username=user.username))
return HttpResponse(status=204)
# Post must be via GET or PUT
else:
return JsonResponse({
"error": "GET or PUT request required."
}, status=400)
I wanted to add a return HttpResponseRedirect(reverse("index"))
or return redirect(reverse('index'))
underneath the post.like.add and post.like.remove to redirect to the current page, but this makes the return HttpResponse(status=204)
unreachable which results in this error:
Forbidden (CSRF token missing.): /
[28/Mar/2023 22:35:55] "PUT / HTTP/1.1" 403 2506
Comments
Post a Comment