我对Django和DRF很陌生。 我有一个带有图像和ForeignKey字段的 Model 。
class Image(models.Model):
image = models.ImageField(blank=False, null=False)
predicted_result = models.ForeignKey(PredictedIllness, on_delete=models.CASCADE)
序列化器:
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields =['image','predicted_result']
和视图:
class UploadImage(APIView):
def post(self, request, format=None):
serializer = ImageSerializer(data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response('Classified', status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def classify_image(self, image_file, image):
image = open_image(image)
pred_class, pred_idx, outputs = fastAi_learner.predict(image)
print(pred_class.data.item())
return pred_class.data.item()
因此,当我使用POST请求拍摄时,一切正常,并且响应:返回带有状态201的“分类”。
但是,我要做的是使用classify_image函数对图像自己进行分类。
def post(self, request, format=None):
try:
im = pilImage.open(request.data['image'])
if im.load():
predicted_condition = self.classify_image(image_file=request.data['image'].name,
image=request.data['image'])
request.data['predicted_result'] = predicted_condition
serializer = ImageSerializer(data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(1, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
except IOError:
return Response('problems with image', status=status.HTTP_400_BAD_REQUEST)
出于某种原因,当我以完全相同的要求从邮递员射击时,收到以下400条回复:
{
"image": [
"Upload a valid image. The file you uploaded was either not an image or a corrupted image."
]
}
什么会导致引发此错误?因为我发送的图像完全相同。以及如何将自定义数据(不是来自请求)添加到序列化器本身/正确地请求?