django - React - Axios:数据未保存在数据库中
django - React - Axios: Data not being saved in database
我正在尝试使用 axios post 请求通过 React js 组件创建产品。
在 django 日志中,我看到一个 OPTION 请求获得 200 状态代码,但数据未保存在数据库中。
当通过 postman 执行时,它工作正常,这让我认为问题出在 axios 请求中。
models.py
class Product(models.Model):
title = models.CharField(max_length=32)
notes = models.TextField()
picture = models.ImageField(upload_to='product_images', null=True, blank=True)
amount = models.IntegerField(default=0)
@receiver(post_save, sender='product.Transaction')
def update_amount(sender, **kwargs):
product = Product.objects.get(title=kwargs['instance'].product)
if kwargs['instance'].transaction_type == 'IN':
product.amount += kwargs['instance'].amount
product.save()
else:
if product.amount - kwargs['instance'].amount > 0:
product.amount = product.amount - kwargs['instance'].amount
product.save()
def __str__(self):
return self.title
views.py
class ProductCreateView(generics.CreateAPIView):
serializer_class = ProductSerilizer
permission_classes = (permissions.IsAuthenticated,)
queryset = Product.objects.all()
serializers.py
class ProductSerilizer(ModelSerializer):
class Meta:
model = Product
fields = '__all__'
settings.py
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'product',
'rest_framework',
'corsheaders',
'rest_framework.authtoken'
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
'DATETIME_FORMAT': '%d-%m-%Y',
}
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True
AddProducts.js
import React, {useState} from 'react';
import axios from 'axios'
import { useNavigate } from "react-router-dom";
function AddProduct() {
const [medicineTitle, setMedicineTitle] = useState('');
const [description, setDescription] = useState('');
const [medicineImage, setMedicineImage] = useState('');
const navigate = useNavigate();
const addToForm = async () => {
let formfield = new FormData()
formfield.append('title', medicineTitle)
formfield.append('notes', description)
formfield.append('picture', medicineImage)
formfield.append('amount', 0)
await axios({
method: 'post',
url: 'http://127.0.0.1:8000/api/protuct_create',
headers: {
'Access-Control-Allow-Origin': '*',
'Authorization': 'Token ********************************',
},
data: formfield,
}).then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
}
return (
<div className='container'>
<h5>Agregar un medicamento</h5>
<form encType='multipart/form-data' >
<div className="mb-3">
<label className="form-label">Nombre del medicamento</label>
<input
type="text"
className="form-control"
id="title"
aria-describedby="title"
placeholder='Introduce nombre del medicamentos'
name='title'
value={medicineTitle}
onChange={(e) => setMedicineTitle(e.target.value)}
/>
</div>
<div className="mb-3">
<label className="form-label">Descripción</label>
<textarea
className="form-control"
id="medicineDescription"
placeholder='Introduce una descripción'
name="medicineDescription"
aria-describedby="Description"
onChange={(e) => setDescription(e.target.value)}
>
</textarea>
</div>
<div className="mb-3">
<label className="form-label">Foto </label><br/>
<input
type="file"
className="form-control"
id="image"
aria-describedby="image"
placeholder='Selecciones la imagen'
name='image'
value={medicineImage}
onChange={(e) => setMedicineImage(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary" onClick={addToForm}>Submit</button>
</form>
</div>
);
}
export default AddProduct;
我想通了。
这些问题与 CORS headers 有关。我必须设置 API.
允许的 headers
通过在 django 后端添加以下代码 my settings.py,它允许从前端发送的请求:
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
我正在尝试使用 axios post 请求通过 React js 组件创建产品。
在 django 日志中,我看到一个 OPTION 请求获得 200 状态代码,但数据未保存在数据库中。
当通过 postman 执行时,它工作正常,这让我认为问题出在 axios 请求中。
models.py
class Product(models.Model):
title = models.CharField(max_length=32)
notes = models.TextField()
picture = models.ImageField(upload_to='product_images', null=True, blank=True)
amount = models.IntegerField(default=0)
@receiver(post_save, sender='product.Transaction')
def update_amount(sender, **kwargs):
product = Product.objects.get(title=kwargs['instance'].product)
if kwargs['instance'].transaction_type == 'IN':
product.amount += kwargs['instance'].amount
product.save()
else:
if product.amount - kwargs['instance'].amount > 0:
product.amount = product.amount - kwargs['instance'].amount
product.save()
def __str__(self):
return self.title
views.py
class ProductCreateView(generics.CreateAPIView):
serializer_class = ProductSerilizer
permission_classes = (permissions.IsAuthenticated,)
queryset = Product.objects.all()
serializers.py
class ProductSerilizer(ModelSerializer):
class Meta:
model = Product
fields = '__all__'
settings.py
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'product',
'rest_framework',
'corsheaders',
'rest_framework.authtoken'
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
'DATETIME_FORMAT': '%d-%m-%Y',
}
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True
AddProducts.js
import React, {useState} from 'react';
import axios from 'axios'
import { useNavigate } from "react-router-dom";
function AddProduct() {
const [medicineTitle, setMedicineTitle] = useState('');
const [description, setDescription] = useState('');
const [medicineImage, setMedicineImage] = useState('');
const navigate = useNavigate();
const addToForm = async () => {
let formfield = new FormData()
formfield.append('title', medicineTitle)
formfield.append('notes', description)
formfield.append('picture', medicineImage)
formfield.append('amount', 0)
await axios({
method: 'post',
url: 'http://127.0.0.1:8000/api/protuct_create',
headers: {
'Access-Control-Allow-Origin': '*',
'Authorization': 'Token ********************************',
},
data: formfield,
}).then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
}
return (
<div className='container'>
<h5>Agregar un medicamento</h5>
<form encType='multipart/form-data' >
<div className="mb-3">
<label className="form-label">Nombre del medicamento</label>
<input
type="text"
className="form-control"
id="title"
aria-describedby="title"
placeholder='Introduce nombre del medicamentos'
name='title'
value={medicineTitle}
onChange={(e) => setMedicineTitle(e.target.value)}
/>
</div>
<div className="mb-3">
<label className="form-label">Descripción</label>
<textarea
className="form-control"
id="medicineDescription"
placeholder='Introduce una descripción'
name="medicineDescription"
aria-describedby="Description"
onChange={(e) => setDescription(e.target.value)}
>
</textarea>
</div>
<div className="mb-3">
<label className="form-label">Foto </label><br/>
<input
type="file"
className="form-control"
id="image"
aria-describedby="image"
placeholder='Selecciones la imagen'
name='image'
value={medicineImage}
onChange={(e) => setMedicineImage(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary" onClick={addToForm}>Submit</button>
</form>
</div>
);
}
export default AddProduct;
我想通了。
这些问题与 CORS headers 有关。我必须设置 API.
允许的 headers通过在 django 后端添加以下代码 my settings.py,它允许从前端发送的请求:
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]