The implementation of a Like Button in Django using JS and DOM resulted in a 404 error

I am facing an issue with the 'live' like/unlike button functionality in Django and JavaScript DOM

Upon clicking the button, an error is triggered

POST http://127.0.0.1:8000/like/24 404 (Not Found)
likePost @ javascripts.js:24
(anonymous) @ javascripts.js:40
javascripts.js:7 

I am unsure whether the problem lies within the 'await fetch' function or if I have incorrectly used a class or id somewhere. Where should I begin troubleshooting?

javascript.js

const reloadPostHTML = async (postId) => {
  const homePageResponse = await fetch(window.location.href);
  const newHTML = await homePageResponse.text();
  const newDocument = new DOMParser().parseFromString(newHTML, "text/html");
  console.log(newDocument)
  const newPostElem = newDocument
    .querySelector(`[data-post-id='${postId}']`)
    .closest(".post");
  const oldPostElem = document
    .querySelector(`[data-post-id='${postId}']`)
    .closest(".post");
  oldPostElem.innerHTML = newPostElem.innerHTML;
  makeLikeButton(oldPostElem.querySelector(".like-button-wrapper"));
};

const likePost = async (postId, csrfToken) => {
    await fetch(`/like/${postId}`, {
      method: 'POST',
      credentials: 'include',
      headers: {
        "X-CSRFToken": csrfToken
      }
    });
    reloadPostHTML(postId);
  };

const makeLikeButton = (elem) => {
  elem.querySelector('button').addEventListener("click", (event) => {
    event.preventDefault();
    const postId = elem.dataset.postId;
    const csrfToken = elem.dataset.csrfToken;
    likePost(postId, csrfToken);
  });
};

const makeLikeButtons = () => {
  for (let elem of document.getElementsByClassName("like-button-wrapper")) {
    makeLikeButton(elem);
  }
};
makeLikeButtons();

urls.py

    path(
        'article_detail/<int:pk>/',
        login_required(
            ArticleDetail.as_view(template_name = "web/article_detail_view.html")
        ),
        name='article_detail'
        ),
    path('like/<int:pk>', views.like, name='like'),

In the views, should I also check "if request.method == "POST":" ? views.py

def like(request, pk):

    article = get_object_or_404(Article, id=request.POST.get("article_id"))
    if article.likes.filter(id=request.user.id).exists():
        article.likes.remove(request.user)
        liked = False
    else:
        article.likes.add(request.user)
        liked = True
    return HttpResponseRedirect(reverse("article_detail", args=[int(pk)]))

and detail_view.py

class .post is included in the structure, hence I have used .closest(".post") in javascript.js

<div class="card post"> ........
                <div class="like-button-wrapper"
          data-post-id='{{ article.pk }}'
          data-csrf-token='{{ csrf_token }}'>

    {% if liked %}
    <button class="btn btn-danger position-relative" type="submit" id="like" name="article_id"
        value="{{article.id}}">
        <i class="bi bi-hand-thumbs-down">
        </i>
    </button>
    {% else %}
    <button class="btn btn-primary position-relative" type="submit" id="like" name="article_id"
        value="{{article.id}}">
        <i class="bi bi-hand-thumbs-up">
        </i>
        <span
            class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
            {{ likes }}
        </span>
    </button>
    {% endif %}
</div>

Answer №1

After some troubleshooting, I discovered that the error 404 was originating from the views.py file, specifically the get_or_404 function.

To resolve the issue, I decided to reconstruct the like function within the views file, and now it is functioning correctly as intended.


def like(request, pk):
    if request.method == "POST":
        #article = get_object_or_404(Article, id=request.POST.get("article_id"))
        article = Article.objects.get(id=pk)

        if article.likes.filter(id=request.user.id).exists():
            article.likes.remove(request.user)
            liked = False
        else:
            article.likes.add(request.user)
            liked = True

    return HttpResponseRedirect(reverse("article_detail", args=[int(pk)]))

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

The React page loads before verifying the clients' permissions

In my application, I am using a Javascript query to fetch the data of the current user. This data is then used to verify the user's access permissions for different pages in my React app with the help of Apollo Client and GraphQL. Unfortunately, ther ...

Browser lacks proper credentials for passport authentication

I'm currently learning how to incorporate user authentication using passport.js. I have successfully set up a basic passport "local" strategy on the server side, along with a single POST route for logging in users. When testing with insomnia, everythi ...

Show error messages from HTML 5 Validation using a software program

Is it possible to manually trigger the HTML 5 validation message using code? As far as I can tell, there isn't a straightforward way to do so directly. However, it seems we can prompt this message by simulating a click on the submit button. I attempt ...

The minification of HTML scripts may cause problems with the <script> tag

Greetings! I have a PHP script that is used to minify the page by removing any comments or spaces. Here is the script: <?php function sanitize_output($buffer) { $search = array( '/\>[^\S ]+/s', '/[^&b ...

Once a WordPress user includes a php file

For the past three days, I've been grappling with this issue... calling on all experts for assistance! I manage four distinct Wordpress membership sites, each with its own branding. My goal is simple - to have a .wav file play the plan's name wh ...

Unpacking the information in React

My goal is to destructure coinsData so I can access the id globally and iterate through the data elsewhere. However, I am facing an issue with TypeScript on exporting CoinProvider: Type '({ children }: { children?: ReactNode; }) => void' is no ...

Tips for effectively utilizing Mongoose models within Next.js

Currently, I am in the process of developing a Next.js application using TypeScript and MongoDB/Mongoose. Lately, I encountered an issue related to Mongoose models where they were attempting to overwrite the Model every time it was utilized. Here is the c ...

What is the most efficient way to optimize the time complexity of a JSON structure?

Here is the input JSON: const data = { "38931": [{ "userT": "z", "personId": 13424, "user": { "id": 38931, "email": "sample", }, } ...

Inspecting Facebook links

Currently working on a website and interested in incorporating a feature similar to what Facebook has. I'm referring to the link inspector, but I'm not entirely sure if that's its official name. Allow me to provide an example to clarify my r ...

Python-JavaScript Integration Problem

I'm a beginner when it comes to Javascript, Python, and PHP. In my Javascript program, I have a button that triggers a Python script and displays the returned value on the screen. My goal is to steer clear of using Jquery and Json. Here are the snipp ...

Turning off strict mode in the bundling process of React with webpack can be achieved by following

I'm facing an issue with my application. It works perfectly in all browsers except for IE, where it throws the following error: 0x800a0416 - JavaScript runtime error: Multiple definitions of a property not allowed in strict mode In my webpack.config ...

A guide on updating div IDs using jQuery sortable when an element is moved by the user

My goal is to use jQuery sortable to allow users to rearrange elements on a page by dragging and dropping them. Each div element has a unique ID, and when the user swaps elements, I want to update the IDs accordingly and alert the new order so it can be sa ...

Experiencing Issues with File Downloading on Express Server with Axios and Js-File-Download Library

I developed a feature on my express server that allows users to download a file easily. app.post("/download", (req, res) => { let file_name = req.body.name; res.download(path.join(__dirname, `files/${file_name}.mp3`), (err) => { ...

I am having trouble with my append function even though I checked the console log and did not see any errors (beginner's inquiry)

As I practice working with functions and dynamically creating input fields, I have encountered an issue where I am unable to append my input field to the form. Despite using console.log() and not seeing any errors, I can't figure out what mistake I ma ...

Executing the AngularJS nested controller only once

I am still new to Angularjs and just started working on an app that has several "projects" each with a local menu displayed on specific pages. The main navbar with footer is located in the Index.html: <body ng-app="ysi-app" ng-controller="MainControlle ...

When I try to insert new data into a MongoDB collection during an update operation, the existing data is being overwritten instead

While updating data, I have a requirement to also add new data. Specifically, I need to append data to an existing object in a for loop that stores data in a database. However, when attempting this, the data is being updated instead of added to the current ...

Guide on adding a button to a mat-table in Angular

I am looking to add a delete button or an Angular trash icon to a mat-table in an Angular application. Can anyone guide me on how to achieve this? Here is my current table code: <mat-table #table [dataSource]="ELEMENT_DATA"> <ng-container cdk ...

Outlining in Three.js

Can I achieve a black outline effect on my 3D models using three.js? I'm looking to create graphics similar to Borderlands 2, with toon shading and distinct black outlines. ...

Utilizing JSON Objects to Populate a Knockout Form

I am looking to populate a form using knockout data-binding from a JSON object. I currently have the values hardcoded in my knockout setup, but what I really want to achieve is dynamically populating the form based on a JSON object. Here is a link to my ...

The Bootstrap modal fails to open

I am currently working on implementing a Navbar button that triggers a Bootstrap modal containing a form. While looking for resources, I stumbled upon a useful script at https://gist.github.com/havvg/3226804. I'm in the process of customizing it to su ...