Django Rest Framework:上传图片

时间:2018-03-09 04:53:33

标签: django python-3.x django-rest-framework postman

我无法将图像保存到图像区域。 的错误

"image": [
    "No file was submitted."
]

models.py

class MyImages(models.Model):
    name = models.CharField(max_length=255)
    image = models.ImageField(upload_to='myphoto', null=False,       max_length=255, blank=False)

views.py

class ImageList(APIView):
    parser_classes = (MultiPartParser, FileUploadParser,)

    def post(self, request):
        file_serializer = MyImageSerializer(data=request.data)
        if file_serializer.is_valid():
            file_serializer.save()
            return Response(file_serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serialiser.py

class MyImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyImages
        fields = ('id', 'name', 'image')

使用postman进行文件上传时,会在view.py中返回文件名而不是文件对象。

我也看过这些线程但没有工作 1 2

2 个答案:

答案 0 :(得分:1)

FileUploadParser使用包含上传文件的request.data密钥填充file

但是,ImageSerializer需要从请求中序列化image

因此,您需要明确指定字段。 e.g。

class ImageFileField(serializers.Field):
    def to_representation(self, obj):
        return obj.image.url

    def to_internal_value(self, data):
        return data['file']


class MyImageSerializer(serializers.ModelSerializer):
    name = serializers.CharField()
    image = ImageFileField(source='*')

    class Meta:
        model = MyImages

答案 1 :(得分:1)

当我尝试重现错误时,我在代码中找不到任何错误 确保取消选中 application/json内容类型
enter image description here

然后邮差控制台将如下,
enter image description here