[Django]-Can't save image to django model

4👍

You can’t directly assign a PIL image to an ImageField like so. You need a little workaround:

from io import BytesIO
from django.core.files.base import ContentFile

image = Image.open(filename)
image = image.resize(size,Image.ANTIALIAS)

image_io = BytesIO()
image.save(image_io, format='jpeg', quality=80) # you can change format and quality

# save to model
image_name = "my_image"
instance.avatar.save(image_name, ContentFile(image_io.getvalue()))

Leave a comment