Utilizing Pagination along with JsonResponse

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.

Answer №1

After some investigation, I was able to identify the error.

I realized that I forgot to include a slash after str:username in the path. The correct format should be:

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

In addition, I decided to remove the int() for both page_number and items_per_page.

These adjustments have resolved the issue. It's interesting how often we discover our mistakes right after seeking help on a forum...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to Capturing a Comprehensive Stack Trace Using Winston 3

Here is how I have configured my logging system: const customFormat = printf(info => { return `${info.timestamp}: ${info.level}: ${info.message}: ${info.err}`; }); const newLogger = winston.createLogger({ level: "info", format: combine( ...

What advantages does the use of $(e).attr(name,value) offer compared to using e.setAttribute(name,value)?

Scenario: The variable "e" represents an element of type "HtmlElement" and not a "css selector" I am referring to any attribute, not just the standard allowed ones like "atom-type" or "data-atom-type". Regardless of the attribute name, will it function wi ...

Attempting to save data to a .txt file using PHP and making an AJAX POST request

I have been facing an issue while trying to save a dynamically created string based on user interaction in my web app. It's just a simple string without anything special. I am using ajax to send this string to the server, and although it reaches the f ...

Incorporate an image into your webpage with the Fetch API by specifying the image link - JavaScript

I've been attempting to retrieve an image using the imageLink provided by the backend server. fetchImage(imageLink) { let result; const url = `https://company.com/internal/document/download?ID=${imageLink}`; const proxyurl = 'https:/ ...

What is the best way to update the state of a different component?

Snippet: var React = require('react'); var RecipeBox = require('./RecipeBox.jsx'); var AddRecipe = React.createClass({ handleClick: function () { RecipeBox.setState({ adding: false }); }, rend ...

Using the Selenium webdriver to reach the bottom of the page by scrolling vertically

Is there a way to determine if I have scrolled to the bottom of the page vertically? I have been using Webdriver and pressing the page down key repeatedly within a for loop, like so: for(int di=0; di<40; di++) { driver.findElement(By.tagName("body ...

AJAX Post data transmission on the network: Enhancing data formatting

For my AJAX post call, I need to format the data differently. The server is expecting the data in a specific format when viewed in Chrome Network Headers details. My task is to update the JavaScript code below to meet this formatting requirement: percenta ...

What is the process for fetching the chosen outcome from a subsequent webpage using HTML?

How can I display selected cities on a different webpage after clicking a button? Currently, I can only get the results on the same page. For example, if a user selects NYC and Delhi, those cities should be displayed on another HTML page. ...

How about this: "Effortlessly upload files by simply dragging and dropping them from your computer to

Currently, I am facing a challenge in uploading a picture from my PC to a website that utilizes a drag and drop interface. Despite using Javascript to open the required link, set properties, and click on the upload field, a file manager window appears wh ...

Prevent the display of cascading div elements by using JavaScript and jQuery scripting

My webpage performs a simple check to verify if Javascript and cookies are enabled on the client's browser. If they are enabled, the script displays the content inside div id="conteudo" and hides the warning message inside div id="aviso". If not, the ...

Incorrect pathing in express.js

I've encountered an issue with my filter while attempting to redirect packages using two express.js routes: app.get('/billdetails/:year/:month/:phoneId', function (req, res, next) { var db = req.db; var year = req.params.year; v ...

Tips for refreshing captcha without the need to refresh the entire page

<img id="imgCaptcha" src="SandCaptcha.aspx?CHA=0azSeOdr7S7gTkFxtL6/5B6h2vj+naZnDR5jl/dvceoJHNXcooHfP2MkoWxPRVWvdK7NJHckH" style="height:60px;width:160px;"> (function() { 'use strict'; function refreshCaptcha() { document.querySe ...

DiscordJS: updating specific segment of JSON object

I am currently working on a Discord bot using discord.JS that involves creating a JSON database with specific values. I'm wondering how I can modify the code to edit a particular object within the JSON instead of completely replacing it. if (message.c ...

Modifying dat.gui to reflect changes made to the selected object

check out this working code I am currently exploring ways to update or refresh dat.gui in order to reflect the changes I make to my selection. My main objective is to generate random cubes and then manipulate a single cube by rotating, scaling, changing p ...

Changing the Flash message to an Alert message in Symfony2: A step-by-step guide

I've encountered a problem where the success message from an action method in Symfony2 Controller appears as a flash message, but I need to display it as an alert or dialogue message according to requirements. I have attempted various solutions witho ...

Step by step guide on moving a scene in Three.js

Is there a way to drag the scene when moving the mouse left or right without rotating the camera? I attempted camera.position.x = mouseX; camera.position.y = mouseY; However, this resulted in the scene rotating. Even changing the position in the sce ...

Issues involving JavaScript and jQuery

As a beginner in the world of JS and jQuery, I have encountered a problem that I am seeking assistance with. I am trying to use a script to insert content into a page, but I am facing a roadblock that I can't seem to overcome. Here's the specific ...

Exploring Quadrics with Marching Cubes in Three.js

I have been attempting to create an applet that displays various types of space quadrics using the Marching Cubes library from three.js to render implicit surfaces. However, the shapes that are being generated do not appear as expected, leading me to belie ...

JavaScript Promise Triggering a Function Automatically

As a newcomer to Javascript promises, I am encountering an issue that has proven elusive in my research through Google and Stack Exchange. It seems that when referencing a function in a .then chain off a promise, I sometimes must enclose that function with ...

Execute an UPDATE query in PostgreSQL for each item in the array

Imagine a scenario where a cart filled with various grocery items, each having a unique ID, is ready for purchase. When the "purchase" button is clicked, an array containing objects of each item in the cart is sent. The number of items in the cart can vary ...