我想同时传递JSON对象和图像,以对django rest api做出反应。
我已经尝试过该论坛和教程中的一些解决方案,但对我而言没有任何作用。以前,我一直在状态字段上使用JSON.stringify,并且可以,但是我无法传递图像,现在我遇到了类似的问题。
postData.js
let formData = new FormData();
const { title, description, image, ingredient, step } = this.state;
formData.append('image', image);
formData.append('title', title);
formData.append('description', description);
formData.append('ingredient', ingredient);
formData.append('step', step);
let conf = {
method: 'post',
body: formData,
headers: new Headers({
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
})
};
fetch('http://127.0.0.1:8000/api/', conf)
.then(res => {
this.props.history.push('/');
})
.catch(err=>{console.log(err)})
serializers.py
class RecipeSerializer(serializers.ModelSerializer):
ingredient = IngredientSerializer(many=True, required=False)
step = StepSerializer(many=True, required=False)
class Meta:
model=models.Recipe
fields=('id', 'title', 'description', 'image', 'ingredient', 'step', )
def create(self, validated_data):
ingredient_data = validated_data.pop('ingredient')
step_data = validated_data.pop('step')
recipe = models.Recipe.objects.create(**validated_data)
for ingredient in ingredient_data:
models.Ingredient.objects.create(recipe=recipe, **ingredient)
for step in step_data:
models.Step.objects.create(recipe=recipe, **step)
return recipe
views.py
class ListRecipes(generics.ListCreateAPIView):
queryset = Recipe.objects.all()
serializer_class = RecipeSerializer
class DetailRecipe(generics.RetrieveUpdateDestroyAPIView):
queryset = Recipe.objects.all()
serializer_class = RecipeSerializer
我总是收到 POST http://127.0.0.1:8000/api/ 400(错误请求)错误。
-编辑-
我更改了代码并创建了用于上传图像的新端点,从技术上讲,它可以正常工作,但是我试图将图像并创建配方ID附加到FormData()中,当我将其登录到控制台时,它包含了两者,但是当我在仅包含图像的后端打印。
postData.js
formData.append('id', this.state.id);
formData.append('image', image, image.name);
for(let key of formData.entries()){
console.log(key);
}
let data = {
method: 'post',
body: formData,
headers: new Headers({
'Accept': 'application/json'
})
};
fetch('http://127.0.0.1:8000/api/images/', data)
.then(res => {
console.log(res);
})
.catch(err=>{
console.log(err);
})
serializers.py
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = models.Image
fields = ('id', 'image', )
def create(self, validated_data):
print(validated_data)
recipe = models.Recipe.objects.get(id=validated_data.id)
image = models.Image.objects.create(recipe=recipe, **validated_data)
return image