I am currently working on the CS50W Network project, and implementing the loading of all posts via API (path is created). When accessing the JsonResponse data directly through the path in the search bar, all data shows up as expected, but when using fetch to access the same data in Javascript, no response is received.
Below is the code:
document.addEventListener('DOMContentLoaded', ()=>{
// Default: Load All posts (Page 1)
load_posts('all', 1);
});
function load_posts(page_type, page_num){
document.querySelector('#all-posts').innerHTML = "";
// Loads all posts
fetch(`/Load/Posts/all/1`)
.then(response => response.json())
.then(data => {
let posts = data.responce;
let direction = data.direction;
console.log(posts);
posts.forEach(post => {
const new_post_div = document.createElement('div');
new_post_div.className = 'card-post';
new_post_div.innerHTML = `
<h3>${post.user}</h3>
<button href="#" id="edit">Edit</button>
<div id="display_contents">
<p>${post.content}</p>
</div>
<div id="timestamp" style="color:#d3d3d3">${post.timestamp}</div>
<div id="likes-container">
<button id="like-button" onclick=like_post(${post.id})><h3 style="color:#d4d4d4">♥</h3></button>
<span>${post.likes}</span>
</div>
`;
document.querySelector("#all-posts").appendChild(new_post_div);
});
});
}
Here is the Python view that sends the JsonResponse data:
def load_posts(request, page_type, page_num):
current_user = request.user
# Determining type of page
if page_type == 'all' :
posts = Post.objects.all()
elif page_type == 'following':
profile = Profile.objects.filter(user=current_user)
followings = profile.following
posts = Post.objects.filter(user__in=followings)
elif page_type == 'user':
posts = Post.objects.filter(user=current_user)
posts = posts.order_by('-timestamp')
else:
return JsonResponse({'error':'Invalid Request!'}, status=200)
#Pagination
p = Paginator(posts, 10)
page = p.page(page_num)
pages = p.num_pages
response = [post.serialize() for post in page]
prev = next = fwd = bwd = False
if page.has_next():
next = page.next_page_number()
if page_num < pages:
fwd = True
if page.has_previous():
prev = page.previous_page_number()
if page_num > 1:
bwd = True
direction = {
'prev':prev,
'next':next,
'fwd':fwd,
'bwd':bwd
}
return JsonResponse({
'response':response,
'direction':direction
})```