Hi Everybody,
I try to use the serializer to save an image in my model as following:
def save_file(file,owner):
data ={}
pic = None
myfile = file
is_image(myfile)
data['image'] = file
data['owner'] = owner
s = ImageSerializer(data=data)
if s.is_valid():
logger.error("image {filename} saved".format(filename =
file.name))
pic = s.save()
else :
logger.error("image {filename} ERROR {errors}".format(filename =
file.name, errors = s.errors))
return pic
Model :
class Image(models.Model):
image = models.ImageField(upload_to=path_and_rename, max_length=500)
owner = models.CharField(max_length=100)
Serializer :
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = Image
fields = '__all__'
The save function does not work because of the call of the function is_image(file) :
def is_image(myfile):
try:
im = Image.open(myfile)
im.verify()
except Exception:
raise Execption('Invalid image')
When I call this function the serializer fails as following :
"POST /image HTTP/1.1" 200 22897
image single_file.jpg ERROR {'image': [ErrorDetail(string='Upload a valid image. The file you uploaded was either not an image or a corrupted image.', code='invalid_image')]}
If I comment the call, the serializer save the file correctly.
According to im.verify(), the file is a valid image. but then it seems like Pillow corrupt the file somehow and the serializer can not save it.
I have tried im.load(), im.close(), im.fp.close()
Nothing works.
Can someone help me? Where is my mistake?
Thank you