【问题标题】:"The submitted data was not a file. Check the encoding type on the form." validation error, despite uploading correct file (django rest framework)“提交的数据不是文件。请检查表单上的编码类型。”验证错误,尽管上传了正确的文件(django rest 框架)
【发布时间】:2020-12-30 23:28:35
【问题描述】:

我正在尝试在我的 api 中创建用于上传图像的端点,我正在使用 django rest 框架构建该端点。 当我尝试使用邮递员测试端点时,我得到了响应

"image": [
        "The submitted data was not a file. Check the encoding type on the form."
    ]

状态码为 400。 当我尝试将带有图像的变量打印到控制台时,我得到了

[<TemporaryUploadedFile: test.jpg (image/jpeg)>]

我查看了一些教程,我认为我正确地发送了文件。 That is my post man configuration

这就是风景

class ImageView(APIView):
    parser_classes = (MultiPartParser, )
    permission_classes = (IsAuthenticated, IsRestaurant)

    def post(self, request, *args, **kwargs):

        data = {
            'image': request.data.pop('image'),
            'info': request.user.info.pk
        }
        file_serializer = RestaurantImageSerializer(data=data)

        if file_serializer.is_valid():
            file_serializer.save()
            return Response(status=status.HTTP_201_CREATED)
        else:
            return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

序列化器

class RestaurantImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = RestaurantImage
        fields = '__all__'

和模型

class RestaurantImage(models.Model):
    info = models.ForeignKey(RestaurantInfo, related_name='images', on_delete=models.CASCADE)
    image = models.ImageField()

    def __str__(self):
        return self.image.name

【问题讨论】:

    标签: django file-upload django-rest-framework


    【解决方案1】:

    您的 Postman 配置可能有问题,请尝试删除所有错误或不必要的标题。我认为您只需要授权即可。这也可以帮助你:https://stackoverflow.com/a/41435972/4907382

    【讨论】:

      猜你喜欢
      • 2019-04-30
      • 2021-09-30
      • 2016-10-31
      • 2015-12-13
      • 2020-08-30
      • 1970-01-01
      • 2013-12-14
      • 2015-03-18
      • 1970-01-01
      相关资源
      最近更新 更多