javascriptdjangodjango-paginationjsonresponse

Using Pagination with JsonResponse


I'm currently working on CS50W Network project which is basically a social media clone.

I want to get different objects via a fetch API request, which is working fine. But after I implemented Pagination I get a 404 not found.

When The DOM of the index page is loaded I call the getPosts function passing in '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 path for the API is:

path("get_post/<str:username>", views.get_post, name="all_posts"),

My view function to get the requested Posts and handle the Pagination:

@login_required
def get_post(request, username):

    # get all posts
    if username == "all":
        posts = Post.objects.all()
    
    elif username == "following":
        posts = Post.objects.exclude(user=request.user)

    else:
        # get user
        user = User.objects.get(username=username)
        posts = Post.objects.filter(user=user)

    # change button color
    for post in posts:
        if post.likes.filter(id=request.user.id).exists():
            post.liked = True
            post.save()
        else:
            post.liked = False
            post.save()

    # order posts in reverse chronological order
    posts = posts.order_by("-timestamp").all()

    # Get the current page number and the number of items per page from the query parameters
    page_number = int(request.GET.get('page', 1))
    items_per_page = int(request.GET.get('per_page', 10))
    
    # Paginate the posts based on the page number and the number of items per page
    paginator = Paginator(posts, items_per_page)
    page_obj = paginator.get_page(page_number)

    # Create a list of serialized posts for the current page
    serialized_posts = [post.serialize() for post in page_obj]

    # Return a JSON response that includes the serialized posts and pagination metadata
    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 received data gets handed over to the displayPosts function:

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));
  }

this function is supposed to append the Posts to the DOM:

function displayPosts(posts) {

    // create a div element for each post
    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> 
        `;
        // append div to posts-view
        document.querySelector('#posts-view').append(div);
        // get the button
        button = document.querySelectorAll('button[pk="'+post['id']+'"]')[0];
        // change button color
        if (post.liked == true){
          button.classList.add('liked')
        }
        else
          button.classList.remove('liked')
    });
}

In the browser console I get a 404 not found, pointing to the fetch.

I am not sure why...

As you can see, I have not added the page navigation buttons yet.


Solution

  • I found the mistake

    I forgot the slash after str:username in the path, its supposed to be:

    path("get_post/<str:username>/", views.get_post, name="all_posts"),
    

    and I also removed the int() for the page_number and items_per_page.

    now its working fine. It’s always the same, right after I Post a question in a forum I find the mistake right away…