Currently, I am working on a project called CS50W Network, which is essentially a clone of a social media platform.
I have implemented a fetch API request to retrieve different objects, and it was working fine. However, once I added Pagination, I started receiving a 404 not found error.
On the index page, when the DOM is loaded, I call the getPosts function with 'all' as the username and currentPage:
document.addEventListener('DOMContentLoaded', function() {
// By default, getPosts
getPosts('all', currentPage);
});
let currentPage = 1;
const itemsPerPage = 10;
function getPosts(username, page) {
// Make a GET request to the API endpoint
fetch(`/get_post/${username}/?page=${page}&per_page=${itemsPerPage}`)
.then(response => response.json())
.then(data => displayPosts(data.data))
.catch(error => console.error(error));
}
The API path is as follows:
path("get_post/<str:username>", views.get_post, name="all_posts"),
The view function to handle requested posts and pagination is shown below:
@login_required
def get_post(request, username):
# Retrieve all posts
if username == "all":
posts = Post.objects.all()
elif username == "following":
posts = Post.objects.exclude(user=request.user)
else:
user = User.objects.get(username=username)
posts = Post.objects.filter(user=user)
for post in posts:
if post.likes.filter(id=request.user.id).exists():
post.liked = True
post.save()
else:
post.liked = False
post.save()
posts = posts.order_by("-timestamp").all()
page_number = int(request.GET.get('page', 1))
items_per_page = int(request.GET.get('per_page', 10))
paginator = Paginator(posts, items_per_page)
page_obj = paginator.get_page(page_number)
serialized_posts = [post.serialize() for post in page_obj]
return JsonResponse({
'data': serialized_posts,
'meta': {
'page': page_obj.number,
'per_page': items_per_page,
'total_pages': paginator.num_pages,
'total_items': paginator.count
}
})
The retrieved data is then passed to the displayPosts function:
function getPosts(username, page) {
fetch(`/get_post/${username}/?page=${page}&per_page=${itemsPerPage}`)
.then(response => response.json())
.then(data => displayPosts(data.data))
.catch(error => console.error(error));
}
This function appends the posts to the DOM:
function displayPosts(posts) {
posts.forEach(post => {
let div = document.createElement('div');
div.className = "card";
div.innerHTML = `
<div class="card-body">
<a class="card-title" id="user-link" href="profile/${post['username']}"><strong><h6>${post['username']}</h6></strong></a>
<h7 class="card-subtitle mb-2 text-muted">${post['timestamp']}</h7>
<p class="card-text">${post['text']}</p>
<button class="card-text like-button" pk="${post['id']}" onclick="like_post(${post.id});"><h3> ♥ </button> </h3>
<span class="like-count" pk="${post['id']}">${post['likes']}</span>
</div>
`;
document.querySelector('#posts-view').append(div);
button = document.querySelectorAll('button[pk="'+post['id']+'"]')[0];
if (post.liked == true){
button.classList.add('liked')
} else {
button.classList.remove('liked')
}
});
}
In the browser console, I see a 404 not found error related to the fetch request. I am unsure why this is happening...
As you can see, I have not yet added the page navigation buttons.