我无法将图像保存到图像区域。 的错误
"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中返回文件名而不是文件对象。
答案 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)