Django外键字段未使用React Select下拉列表中的选定值进行更新



我的问题跟踪项目中有一个网页,允许项目经理将用户分配给项目。我使用React Select允许经理从下拉列表中选择一个用户。当他们单击添加用户按钮时,所选的值将通过api调用发送到后端。我有一个名为assignuser的APIView,它接收post请求并更新我的项目模型中的用户外键字段。

我引用的值是否错误?我曾尝试将selectedValue.value发送到我的后端,但它一直显示为未定义。请记住,当您控制台.log selectedValue时,显然{label: "...", value: "..."}都在selectedValue中。这也适用于project.js中发送到manageusers.js的SV;成功地将其发送到我的APIView并更新特定项目的用户。

project.js

manageusers.js

Django后端

class assignuser(APIView):
serializer_class = ProjectSerializer
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
user = serializer.data.get('user')
project_name = serializer.data.get('project_name')
project = Project.objects.get(name=project_name)
project.user = user
project.save(update_fields=['user'])
return Response(ProjectSerializer(project).data, status=status.HTTP_201_CREATED)
else:
return HttpResponse("Incorrect Credentials")

manageusers.js

import React, { Component } from "react";
import { useState, useEffect } from "react";
import { Grid, TextField, Button, Typography } from "@material-ui/core";
import { FixedSizeList as List } from 'react-window';
import css from './style.css';
import Select from 'react-select';
import {useLocation} from "react-router";
const manageusers = () => {
const [role, setRole] = useState([]);
const location = useLocation();
const [project_name, setProjectName] = useState();
const [selectedValue, setSelectedValue] = useState()
const rolelist = [];
const handleChange = obj => {
setSelectedValue(obj);
}
useEffect(() => {
fetch("/api/manageroles")
.then((response) => response.json())
.then((data) =>{
setRole(data)
})
}, [])
const post = () => {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json"},
body: JSON.stringify({
user: selectedValue,
project_name: project_name
}),
};
fetch("/api/assignuser",requestOptions)
.then((response) => response.text())
.then((data) =>{

})
.catch((error) => {
console.log(error)
});
}
const Name = () => {
return (
<div>
<Grid item xs={3}>
<Typography component="h5" variant="h5">
{setProjectName(location.state.project_name)}
</Typography>
</Grid>  
</div>
)

}
return (
<div>  
{role.forEach(function(element) {
rolelist.push({ label:element.username, value: element.username })
})}
<Select
value={selectedValue}
options={rolelist}
onChange={handleChange}
isOptionDisabled={option => option.isDisabled}
/>
<div class="ex1">
{role && role.map(roles => (
<Grid item xs={3}>
<Typography component="h5" variant="h5">
<h5> {roles.username} </h5>
</Typography>
</Grid>
))}
</div>
<div>
<Button onClick={() => post()}> Add User</Button>
</div>
<Name/>
</div>
);

}
export default manageusers;

project.js

import React, { Component } from "react";
import { useState, useEffect } from "react";
import { Grid, TextField, Button, Typography } from "@material-ui/core";
import {
BrowserRouter as Router,
Link,
Route,
Switch,
} from 'react-router-dom';
import Select from 'react-select';
const project = () => {
const [name, setName] = useState();
const [description, setDescription] = useState();
const [projects, setProjects] = useState([]);
const [selectedValue, setSelectedValue] = useState(null)
const projectlist = [];

const handleChange = obj => {
setSelectedValue(obj);
}
const post = () => {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json"},
body: JSON.stringify({
name: name,  
description: description,
}),
};
fetch("/api/newProject",requestOptions)
.then((response) => response.json())
.then((data) =>{

})
}
useEffect(() => {
fetch("/api/manageprojects")
.then((response) => response.json())
.then((data) =>{
setProjects(data)
})
}, [])
return (
<div>
{projects.forEach(function(element) {
projectlist.push({ value: element.name })
})}
<body>
<Select 
value={selectedValue}
options={projectlist}
onChange={handleChange}
isOptionDisabled={option => option.isDisabled}
/>
<form action="#" method="POST">
<TextField onChange={(e) => setName(e.target.value)}> </TextField>
<br>
</br>
<TextField onChange={(e) => setDescription(e.target.value)}> </TextField>
<br>
</br>
<Button onClick={() => post()}> Create New Project </Button>
</form>
</body>
<div>
{projects && projects.map(project => (
<Grid item xs={3}>
<Typography component="h5" variant="h5">
<h5> {project.name} </h5>
<h5> {project.description} </h5>
</Typography>
</Grid>
))}
</div>
<Link to={{
pathname: '/manageusers',
state: { 
project_name: selectedValue
}
}}>Manage Users
</Link>
</div>
);
}


export default project;

项目模型

class Project(models.Model):
name = models.CharField(max_length=50, unique=True)
description = models.CharField(max_length=50, unique=True)
user = models.ForeignKey(Users, null=True, blank=True, 
on_delete=models.CASCADE)

您可以执行此

class assignuser(APIView):
serializer_class = ProjectSerializer
def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
project = serializer.validated_data.get("project_name")
project.user = serializer.validated_data.get("user")
project.save()
return Response(ProjectSerializer(project).data, status=status.HTTP_201_CREATED)
else:
return HttpResponse("Incorrect Credentials")
fetch("/api/assignuser",requestOptions)
.then((response) => response.text())
.then((data) =>{
setRole([...role, data])    
})
.catch((error) => {
console.log(error)
});

或者你可以添加新的价值,而不需要从后端获取新的数据,

为什么我要选择这个选项,当你把数据发送到后端时,它会自动为该用户保存,当用户重新加载将显示的页面值时,它仍然是相同的

const post = () => {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json"},
body: JSON.stringify({
user: selectedValue,
project_name: project_name
}),
};
fetch("/api/assignuser",requestOptions)
.then((response) => response.text())
.then((data) =>{
setRole([...role, {label: project_name, value: project_name}])
})
.catch((error) => {
console.log(error)
});
}

base.js

const Base = () => {
const [selectedValue, setSelectedValue] = React.useState()
return (
<div>
<ManagerUser selectedValue={selectedValue} setProjectName={setSelectedValue}/>
<Project selectedValue={selectedValue} setProjectName={setSelectedValue}/>
</div>
)
}

project.js

import React, { Component } from "react";
import { useState, useEffect } from "react";
import { Grid, TextField, Button, Typography } from "@material-ui/core";
import {
BrowserRouter as Router,
Link,
Route,
Switch,
} from 'react-router-dom';
import Select from 'react-select';
const project = (props) => {
const {selectedValue,setSelectedValue} = props
const [name, setName] = useState();
const [description, setDescription] = useState();
const [projects, setProjects] = useState([]);
const projectlist = [];

const handleChange = obj => {
setSelectedValue(obj);
}
const post = () => {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json"},
body: JSON.stringify({
name: name,  
description: description,
}),
};
fetch("/api/newProject",requestOptions)
.then((response) => response.json())
.then((data) =>{

})
}
useEffect(() => {
fetch("/api/manageprojects")
.then((response) => response.json())
.then((data) =>{
setProjects(data)
})
}, [])
return (
<div>
{projects.forEach(function(element) {
projectlist.push({ value: element.name })
})}
<body>
<Select 
value={selectedValue}
options={projectlist}
onChange={handleChange}
isOptionDisabled={option => option.isDisabled}
/>
<form action="#" method="POST">
<TextField onChange={(e) => setName(e.target.value)}> </TextField>
<br>
</br>
<TextField onChange={(e) => setDescription(e.target.value)}> </TextField>
<br>
</br>
<Button onClick={() => post()}> Create New Project </Button>
</form>
</body>
<div>
{projects && projects.map(project => (
<Grid item xs={3}>
<Typography component="h5" variant="h5">
<h5> {project.name} </h5>
<h5> {project.description} </h5>
</Typography>
</Grid>
))}
</div>
<Link to={{
pathname: '/manageusers',
state: { 
project_name: selectedValue
}
}}>Manage Users
</Link>
</div>
);
}


export default project;

最新更新