New project was successfully generated, but the information is missing when transmitted from React to Django API

I recently developed a React + Django application and implemented a basic CRUD feature. Everything was working smoothly until I encountered an issue while creating a project and storing it in the Django database. When I view the project at projects/list, only the delete button and image field are displayed, which is not what I intended. I specifically want the title and body fields to be visible.

This snippet is from views.py

class CreateProjectView(viewsets.ModelViewSet):
    serializer_class = ProjectSerializer

    def post(self, request):
        project = ProjectSerializer(data=request.data)
        if project.is_valid(raise_exception=True):
            project.save()
            return Response(project.data)

urls.py

create_project = CreateProjectView.as_view({"get": "post"})
urlpatterns = [
   path("project/create", create_project, name="create-project"),
]

Also, let's take a look at CreateProject.js

import React, { useState } from 'react'

const CreateProject = () => {

    let [project, setProject] = useState([])
    
    let [title, setProjectTitle] = useState("")
    let [body, setProjectBody] = useState("")
    
    const handleChangeTitle = (value) => {
        setProjectTitle(project => ({ ...title, 'title': value}))
        console.log("Title:", value)
    }
    
    const handleChangeBody = (value) => {
        setProjectBody(project => ({ ...body, 'body': value}))
        console.log("Body: ", value)
    }


    let createProject = async () => {
        fetch('http://localhost:8000/api/project/create', {
            method: "POST",
            headers: {
                'Content-Type': "application/json"
            },
            project: {
                "title": title,
                "body": body
            }
        })
    }
    
    let handleSubmit = () => {
        setProject(project)
        
        createProject()
    }

  return (
    <div>
        <h3>Title</h3>
        <input type="text" name="title" onChange={e => {handleChangeTitle(e.target.value)}} defaultValue={project?.title} />
        <br />
        <h3>Body</h3>
        <input type="text" name="body" onChange={e => {handleChangeBody(e.target.value)}} defaultValue={project?.body} />
        <br/>
        <br/>
        <br/>
        
        <button onClick={createProject}>Submit</button>
    </div>
  )
}

export default CreateProject

Last but not least, let's check ProjectViewSet in view.py

class ProjectView(viewsets.ModelViewSet):
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer

I expected the title and body fields along with their content to be displayed on the created project page.

Answer №1

After trying numerous solutions with no success, I finally discovered the issue in the CreateProject.js component within the createProject() function. Here is how I resolved it: Initially, I was sending the data fields like this:

title: project.title,
body: project.body,

However, I should have been sending them as:

body: JSON.stringify({
  title: project.title,
  body: project.body,
})

I attempted to remove the JSON.stringify and only leave it as an empty object like this:

body: {
  title: project.title,
}

But it had to be done the previous way. In any case, this is the correct method for making POST requests from React to Django using React Functions:

let updateProject = async () => {
        fetch(`http://localhost:8000/api/project/update/${projectId}`, {
            method: "PUT",
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                title: project.title,
                body: project.body
            })
        })
    }

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

Changing the CSS background in React when updates occur

Currently working on toggling the CSS background image within this React application. The images have been successfully imported and a variable called "image" is set to the imported image as the iteration increases/decreases with each click. The issue I&a ...

Can all anchor tags properties on a website be simultaneously changed?

Recently, I discovered that using target="_blank" in anchor tags can leave a website vulnerable to security risks, and the recommended alternative is to use rel="noopener". In my current web project, all anchor tags are currently utilizing the target attri ...

"Challenges encountered when trying to populate a select field with information retrieved from

I am currently working on a project using NextJS version 13.4.7 with react, and I am facing an issue while trying to update data in a select field with information fetched from an API call. Upon initial page load, I have set a default option field and valu ...

JQuery magic: Enhancing a div's visibility with animated mouseover effects

I'm trying to figure out how to animate a div on mouseover, specifically making it fade in/appear slowly. I believe I need to use the .animate function or something similar. $("#logo").mouseover(function() { $("#nav").css('visibility',&apos ...

Timeout set to run indefinitely

Looking at the code snippet below, it seems to be running at a frame rate of 60 frames per second. If any button is clicked, the variable isjump will be set to true and the following code will start executing. The goal here is to exit the jump() function a ...

What is the process for obtaining a compilation of warnings from the next.js terminal?

While running my project on VScode, I noticed a series of warnings appearing in the terminal. One specific warning that caught my attention is: The `bg-variant` mixin has been deprecated as of v4.4.0. It will be removed entirely in v5. on line 8 ...

Is it possible to view the object sent from AJAX to PHP in PHP using a debugger?

I'm facing an issue where I am making an AJAX call to a PHP file, sending a JSON object as a parameter from JavaScript. The PHP file is supposed to perform some logic with the object and return it using json_encode('whatever');. However, the ...

In what situations is it essential to utilize the `rerender` function in the React Testing Library?

In the past, my team and I usually focused on writing React Testing Library (RTL) tests for the main parent components that contained numerous nested child components. This approach made sense and proved to be effective. The child components in question we ...

Autocomplete feature integrated within search bar

I'm currently experimenting with merging MUI autocomplete and MUI searchbar to create a Searchbar that provides suggestions. I have attempted the following: https://codesandbox.io/s/material-demo-forked-cthpv import React from "react"; impo ...

A guide on utilizing multer-sftp for downloading files

I've been working on this code, but after searching online I still haven't found a way to download a file from the remote server. I can successfully upload files to the server, but downloading them is posing a challenge. var storage = sftpStorag ...

Move a <div> using a handle (without using JQuery)

I devised a plan to create a moveable div with a handle and came up with this code snippet: var mydragg = function() { return { move: function(divid, xpos, ypos) { divid.style.left = xpos + 'px'; divid.style.top = ypos + &apo ...

Offering various language options on a website determined by the URL

I've been contemplating how to add multi-language support to my personal website, which I developed using ExpressJS and NodeJS with EJS as the template engine. Currently, the website is only available in English, but I want to add a German version as ...

How can I switch the visibility of two A HREF elements by clicking on one of them?

Let me break it down for you in the simplest way possible. First off, there's this <a href="#" id="PAUSE" class="tubular-pause">Pause</a> and then we have a second one <a href="#" id="PLAY" class="tubular-play">Play</a> Al ...

When conducting a test, it was found that the JSX element labeled as 'AddIcon' does not possess any construct or call signatures

Here is a code snippet I'm currently working with: const tableIcons: Icons = { Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />), Check: forwardRef((props, ref) => <Check {...props} ref={ref} />) }; const AddIcon ...

Is there a similar effect in jQuery? This is achieved using prototype

Simply click on the comments link. Observe how the comments smoothly appear, as if sliding down. Also, try clicking on 'hide' and see what happens. ...

Extract the element when the mouse is clicked

I'm currently working on developing a Chrome extension with a specific goal in mind: My aim is to capture the username when a user Ctrl-clicks on a username while browsing Reddit, and then transfer that username from the content script page to the ba ...

Are there any alternatives to ui-ace specifically designed for Angular 2?

I am currently working on an Angular2 project and I'm looking to display my JSON data in an editor. Previously, while working with AngularJS, I was able to achieve this using ui-ace. Here is an example of how I did it: <textarea ui-ace="{ us ...

Error encountered in Colab when importing keras.utils: "to_categorical" name cannot be imported

Currently utilizing Google's Colab to execute the Deep Learning scripts from François Chollet's book "Deep Learning with python." The initial exercise involves using the mnist dataset, but encountering an error: ImportError: cannot import name & ...

Display a block by using the focus() method

My objective is : To display a popin when the user clicks on a button To hide the popin when the user clicks elsewhere I previously implemented this solution successfully: Use jQuery to hide a DIV when the user clicks outside of it However, I wanted to ...

Identifying the camera model using getMediaStream

Are there methods available to determine if a user's device has a front, rear, or dual cameras installed? For instance, laptops typically only have a front-facing camera while some devices may have both. I am looking for a way to identify the type of ...