404 Error: JSON POST and GET Request Not Located

I need assistance with setting up an API in Django as I am encountering errors in the JavaScript console. The error messages are:

GET http://127.0.0.1:8000/edit/undefined 404 (Not Found)
POST http://127.0.0.1:8000/edit/undefined 404 (Not Found)

Is there a solution to resolve this issue?

API url:

path("edit/<int:post_id>", views.edit, name="edit")

views.py

def edit(request, post_id):
    try:
        post = Post.objects.get(user=request.user, pk=post_id)
    except Post.DoesNotExist:
        return JsonResponse({"error": "Post does not exist."}, status=404)

    if request.method == "GET":
        return JsonResponse(post.serialize())
    else:  
        return JsonResponse({"error": "Need a GET request."}, status=404)

JavaScript

document.addEventListener('DOMContentLoaded', function(){
    const editButtons = document.querySelectorAll('.edit_button');
    for (const button of editButtons) {
      button.addEventListener('click', () => edit_email());
    }
  });

function edit_email(id){
    console.log("edit button is clicked")
    document.querySelector('#post_itself').style.display = 'none';
    document.querySelector('#date_and_time').style.display = 'none';
    document.querySelector('#likes').style.display = 'none';

    const textarea = document.createElement('textarea');
    //get post
    fetch(`/edit/${id}`)
    .then(response => response.json())
    .then(post => {
        textarea.innerHTML =   `${post.post}`
        document.querySelector('#p_user').append(textarea);
    })

    //save the post
    fetch(`/edit/${id}`,{
        method: 'POST',
        post: JSON.stringify({
            post: textarea.value
        })
    })
}

HTML

{% for post in page_obj.object_list %}
            <div class = "individual_posts">
                <a href="{% url 'username' post.user %}"><h5 id="p_user" class = "post_user">{{ post.user }}</h5></a>
                <h6 id = "post_itself">{{ post.post }}</h6>
                <h6 id="date_and_time" class = "post_elements">{{ post.date_and_time }}</h6>
                <h6 id="likes" class = "post_elements">{{ post.likes }}&#x1F44D;</h6>
                {% if post.user == request.user %}
                    <button id="editButton" class="edit_button">Edit</button>
                {% endif %}
            </div>
        {% endfor %}

I suspect that there may be an issue in how I am passing the id to the API. Could the for loop in the HTML file possibly be causing this problem?

models.py

class User(AbstractUser):
    followers = models.ManyToManyField("self", related_name="users_followers", symmetrical=False)
    following = models.ManyToManyField("self", related_name ="who_user_is_following", symmetrical=False)

    def serialize(self):
        return{
            "followers": self.followers,
            "following": self.following
        }

class Post(models.Model):
    post = models.TextField()
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
    likes = models.IntegerField(default=0)
    date_and_time = models.DateTimeField(auto_now_add=True)

    def serialize(self):
        return{
            "id": self.id,
            "post": self.post,
            "user": self.user,
            "likes": self.likes,
            "date_and_time": self.date_and_time
        }

Answer №1

When calling edit_email without an id parameter, ensure that you include it:

button.addEventListener('click', () => edit_email());

After making the call, you may receive /edit/undefined due to the missing id here:

fetch(`/edit/${id}`)

To rectify this issue, make sure to pass the value when clicking the button, for example:

button.addEventListener('click', (event) => edit_email(event.target.value));

Ensure that the post object has an id key in your loop so that you can attach the value property to the button as post.id.

If encountering a reference error, verify that page_obj.object_list contains an id key for all posts.

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

Node.js poses a challenge when it comes to decoding incoming request data

I am attempting to create a sample login page using the combination of node, express, and angularjs. Displayed below is my login view: <div class="login-page"> <div class="login-page-content"> <div style="margin-top:30px;padding:10px;w ...

Numpad functionality in JQuery malfunctioning post-ajax request

Using the jQuery numpad plugin has been flawless until after an AJAX call. I have tried various functions like on('click') and others, but unfortunately, none of them worked as expected. Apologies for my poor English! You can find the extension l ...

Ways to execute additional grunt tasks from a registered plugin

I am currently in the process of developing a custom Grunt plugin to streamline a frequently used build process. Normally, I find myself copying and pasting my GruntFile across different projects, but I believe creating a plugin would be more efficient. Th ...

Avoiding Rejected Promise: Warning for Error [ERR_HTTP_HEADERS_SENT] due to Issue with setInterval and Axios.post Error Management

I attempted to address this warning by researching online. Unfortunately, I couldn't find a solution, so I am reaching out with this question. The current warning that I am encountering is: (node:39452) UnhandledPromiseRejectionWarning: Error [ERR_H ...

Overlapping problem with setInterval

I am currently working on a project that requires the use of both setInterval and setTimeout. I am using setTimeout with dynamic delays passed to it. While elements are not timed out, I have implemented setInterval to print out numbers. Here is the code ...

``From transitioning from Django templating to implementing a full RESTful architecture?

Looking to convert my django/html/css website to a REST (json) structure. Previously reliant on django template rendering for frontend responses. Interested in how to manage url redirection and incorporate json data into html templates without the use of ...

Prevent the border from shrinking upon being clicked

I'm currently working on customizing an accordion using jQuery for the animation effects. However, I am facing an issue where clicking on the accordion header causes the border around the plus sign to shrink in size as well. My goal is to only have th ...

"Owlcarousel Slider: A beautiful way to showcase

Currently, I am working on a project that involves implementing a slider. Since I lack expertise in JavaScript, I opted to use a plugin called owlcarousel. The challenge I'm encountering relates to the sizing of the container for the items. I'm ...

Exploring the world of jQuery AJAX alongside Google's currency calculator

I'm currently working on a code that utilizes an AJAX call to access the Google currency calculator. The expected outcome is to receive a JSON array that can then be used to gather exchange rate data. Here is the link: http://www.google.com/ig/cal ...

React setState issue experienced only on initial click due to API lag

My goal is to develop a web app using the Poke API to display multiple Pokemon. I have added buttons to allow users to "change the page" and switch the API URL to view the next or previous set of Pokemon. However, I'm facing an issue where the buttons ...

Is it possible to create an online game using JavaScript?

Hey there, I'm interested in creating a simple online game that can be played in the browser. My main question is this: if I want two players to compete against each other online, can I achieve this by using HTML for the front-end and JavaScript for t ...

Unable to find '/images/img-2.jpg' in the directory 'E:React eact-demosrc'

My code is giving me trouble when trying to add an image background-image: url('/images/img-2.jpg'); An error occurred during compilation. ./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src?? ...

Using a function as an argument within an Angular directive

Looking for a solution to pass a promise-returning function into a directive? Here's what I'm currently doing: In the parent controller, I've created a callback: $scope.myCb = function(data) { console.log(data); } Directive Scope: sco ...

"Exploring the process of unsubscribing or disposing of an interval observable based on a certain condition in Angular2 or

I am embarking on the journey into Rx and reactive programming, facing a situation that requires me to continuously monitor a hardware's status by sending a POST request to its REST API every 500ms. The goal is to stop the interval observable once the ...

Trouble with displaying the NVD3 sample chart

I seem to be missing something simple... I've copied the code for an nvd3 example exactly, but I'm getting a blank page without any error messages. Both the nvd3 and d3 libraries are showing up when I check in the console by typing "nv" or "d3", ...

Making an Ajax request with JSON is yielding unexpected variables that cannot be modified or removed

Attempting to make an AJAX call using a script: $.ajax({ url: pageURL, data: loadData, type: 'POST', cache: false, dataType: 'json', success: function (data) { //if the call was successful console.log(su ...

The Resharper guideline "Function Parameter" doesn't allow the usage of AngularJS service names

I have a question regarding naming conventions in my AngularJS app. Currently, all my service names start with an uppercase character. However, I am facing an issue where service parameters must match the service name, but Resharper's JavaScript "Func ...

Issues are arising with the .mouseover functionality within this particular code snippet

Learning Javascript has been a challenge for me so far. I tried following a tutorial, but the result I got wasn't what I expected based on the video. I'm wondering why that is and how I can fix it. I'm aiming to make a box appear suddenly w ...

What is the proper way to display the complete result of aggregating each outcome from the previous iteration within two nested queries in an array using NodeJS and Mongoose?

As a newcomer to both Stackoverflow and NodeJS/Mongoose, I apologize if I make any mistakes or break any rules. Thank you in advance. I'm looking for a function that can return all nearby products based on my current location, which is provided by th ...

Connect jQuery navigation button to a specific web address

Check out this cool jQuery menu script I found: <script type="text/javascript> jQuery(document).ready(function(){ jQuery('#promo').pieMenu({icon : [ { path : "/wp-content/t ...