Home > OS >  JSON POST and GET 404 (Not Found)
JSON POST and GET 404 (Not Found)

Time:07-18

I am trying to create an API in Django but am receiving the following errors message in the JavaScript console.

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

Does anyone know how to fix this problem?

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" >Edit</button>
                {% endif %}
            </div>
        {% endfor %}

I think something might be wrong in the way I am passing in the id to the API, but I am not sure. Could the for loop in the HTML be causing the 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
        }

CodePudding user response:

you call edit_email without id here:

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

of cause, after call you get /edit/undefined on this line:

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

you don't send anything like id, I can imagine it should be something like this:

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

You will also need to pass the value property to the button as post.id assuming that the post object will have an id key in your for loop.

If you are getting a reference error you need to check if page_obj.object_list has an id key for all the posts.

  • Related