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

Top way to include an HTML and javascript file in an Ext.Panel within Sencha Touch

My main goal is to efficiently include external HTML files and display them on an Ext.Panel in Sencha touch 2.3 by creating a wrapper module for the HTML file that can be instantiated using xtype, with an external Javascript file for event handling. Updat ...

The most efficient method for receiving real-time updates from the server to the app is through Angular 7

Currently, I am in the process of developing an Angular 7 messages service (user to user) for my website. The approach I have taken involves receiving updates from the server (Yii2 REST API) every 3 minutes using an interval function (see code snippet belo ...

Looking to remove a row with php, html, and ajax?

Trying to remove a row from an HTML table has been my latest challenge while working with Materialize CSS. Here is what I have so far, where the ID corresponds to the employee ID: https://i.stack.imgur.com/rjwba.png Below is the code snippet: <?php ...

Using Typescript in React to render font colors with specific styling

Attempting to utilize a variable to set the font color within a react component, encountering an error with my <span>: Type '{ style: "color:yellow"; }' is not assignable to type 'HTMLProps<HTMLSpanElement>' The use of yel ...

Implementing multiple functions with the onClick property of a button to validate user input

In a dialog modal, there is a text field where you can enter a title. When you click the 'create' button, it should add an item to a table and close the dialog modal. <Button onClick={createProjectButtonHandler} variant="contained"&g ...

What are some strategies to reduce the frequency of API calls even when a webpage is reloaded?

Imagine I'm utilizing a complimentary API service that has a restriction of c calls per m minutes. My website consists of a simple HTML file with some JavaScript code like the one below: $(function () { //some code function getSomething() { ...

Is there a way for me to access the current templating in AngularJS?

I am looking to retrieve the HTML page as a string after AngularJS has finished rendering the template. My goal is to send this content to the server. .controller('MyCtrl', ['$scope', '$location', function ( $scope, $location ...

How to Store and Retrieve User-specific Data using Express and Mongoose?

Currently, I am developing a small single-page application that allows users to login using PassportJs and Mongoose. One of the main features I am working on is enabling users to log in and have a unique todo/task list associated with each user. I succes ...

Click the "Login" button using Jquery to gain access

Whenever I hit the Login button, a 500 Internal server error pops up in the console. Can someone guide me on the correct way to perform a POST request using jQuery? I would really appreciate any help. <button class="login100-form-btn" type=& ...

What is the reason that when we assign `'initial'` as the value for `display` property, it does not function as intended for list elements?

To toggle the visibility of elements, I have created a unique function that accepts an object and a boolean. Depending on the boolean value, either 'none' or 'initial' is assigned to the 'display' property of the specified obj ...

Exploring ways to verify the related_name attribute in a Django model

Exploring a model: @python_2_unicode_compatible class TelegramUser(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, verbose_name=_('User'), related_name='telegramuser', on_delete=models.CASCADE) ...

A guide to building a dynamic form slider that showcases variable output fields with Javascript

I'm interested in creating a Slider Form that shows different output fields when sliding, using Javascript. Something like this: Could anyone provide suggestions on how to achieve this or share any links related to something similar? I haven't b ...

The Ajax form's malfunction is attributed to JSON, as it throws a parser error indicating a SyntaxError. Specifically, the JSON.parse function encounters an unexpected end of data at line 1, column 1

I understand that this is a commonly asked question, but I have tried all the solutions provided and none of them have worked for me. My specific issue is that I am unable to load a JSON response from the server using AJAX. Here's the setup: my "scrip ...

Converting an Image to Memory Stream in JavaScript

Incorporating the jquery.qrcode library, I am able to create a QR code image that is output in the following format. <img src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAA ...

Loading Objects with Material Textures Ahead in Three.js

I am faced with the challenge of preloading multiple obj+mtl files using Three.js, each with distinct file paths, and I need to trigger another function once all the objects have finished loading. Initially, I attempted to use a boolean variable that woul ...

When attempting to access index.html, the Express Server responds with a "Page Not Found"

I have encountered a problem while trying to run my Index.html file through an Express server. Despite referring to previously asked questions, I couldn't resolve the issue. The error message 'Cannot GET /' keeps popping up. Below is the sn ...

Creating code to ensure a div element is displayed only after a specific duration has elapsed

Can anyone help me with coding to make a div appear on a website after a specific amount of time? Here's an example of what I'm trying to achieve: <div class="container"> <div class="secretpopout"> This is the hidden div that should ...

Ensure that the cursor is consistently positioned at the end within a contenteditable div

I'm working on a project where I need to always set the caret position at the end of the text. By default, this works fine but when dynamically adding text, the caret position changes to the starting point in Chrome and Firefox (Internet Explorer is s ...

Adding Labels to Doughnut Charts in React using Chart.js 2.0

Currently, I'm exploring the world of data visualizations using react, react-chartjs-2, and chart.js version 2.2.1. While searching for a solution to my inquiry, I came across a potentially relevant answer on this link (specifically check out the upda ...

Is JSON.stringify failing to function correctly in Mozilla Firefox?

Currently, I am attempting to convert an object into a string in javascript. After stringifying the object, I have noticed some discrepancies between different browsers. {"jobTypeArray":"[CONTRACT -W2]"} In Firefox and Chrome, the values appear as follow ...