gpt4 book ai didi

python - Django REST Framework 文件上传导致 "Unsupported media type ' multipart/form-data'”错误

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:32 43 4
gpt4 key购买 nike

我是 Django 和 Django REST Framework 的新手。我有以下序列化程序类,我用它来上传文件和其他信息。但是,当我使用上传的文件运行 API 端点时,结果是这样的:

HTTP 415 Unsupported Media Type
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept

{
"detail": "Unsupported media type \"multipart/form-data; boundary=----WebKitFormBoundaryybZ07gjZAqvcsZw3\" in request."
}

我通过谷歌搜索努力尝试解决这个问题,但无法得出解决方案,所以这是我的序列化程序和 API View 。

序列化器:

class ExampleSerializer(serializers.Serializer):

example_id = serializers.IntegerField()
description = serializers.CharField(allow_blank=True)
example_file = serializers.FileField(allow_empty_file=True)

def create_requirement_line(self):
request = self.context['request']

requirement_line = ExampleService().example_method(
example_id=self.validated_data['example_id'],
description=self.validated_data['description'],
example_file=self.validated_data['example_file']
)
return requirement_line

查看:

 class RequirementLineAPIView(BaseCreateAPIView):

serializer_class = ExampleSerializer
parser_classes = (FormParser,)

def post(self, request, format=None,*args, **kwargs):
serializer = self.get_serializer(data=request.data)

if serializer.is_valid():
try:
example_variable = serializer.example_method()
return Response(example_variable, status=status.HTTP_200_OK)

except ValidationError as e:
return Response(e.message, status=status.HTTP_400_BAD_REQUEST)

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

最佳答案

你应该使用 MultiPartParser如果您要发送多部分/表单数据,而不是 FormParser。

关于python - Django REST Framework 文件上传导致 "Unsupported media type ' multipart/form-data'”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36881771/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com