Alexandr Domoryonok Alexandr Domoryonok - 5 months ago 33
Python Question

Can't save image to django model

I try to resize image before save:

from PIL import Image


class UserAvatarUpdate(views.APIView):


serializer_class = UserSerializer

def patch(self, *args, **kwargs):

instance = ExtUser.objects.get(id=self.request.user.id)

instance.avatar = self.request.FILES['file']

size = 100,100

filename = instance.avatar.path

image = Image.open(filename)

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

instance.avatar = image

instance.save()
return Response(
UserSerializer(instance).data,
status=status.HTTP_200_OK
)


but I get the error below on save:


Internal Server Error: /api/v1/update_user_avatar/ Traceback (most
recent call last): File
"/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/core/handlers/base.py",
line 149, in get_response
response = self.process_exception_by_middleware(e, request) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/core/handlers/base.py",
line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/views/decorators/csrf.py",
line 58, in wrapped_view
return view_func(*args, **kwargs) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/views/generic/base.py",
line 68, in view
return self.dispatch(request, *args, **kwargs) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/rest_framework/views.py",
line 466, in dispatch
response = self.handle_exception(exc) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/rest_framework/views.py",
line 463, in dispatch
response = handler(request, *args, **kwargs) File "/home/alexandr/sprutlabs_python/sprutlabs/posts/views.py", line 123,
in patch
instance.save() File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/contrib/auth/base_user.py", line 74, in save
super(AbstractBaseUser, self).save(*args, **kwargs) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/db/models/base.py",
line 708, in save
force_update=force_update, update_fields=update_fields) File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/db/models/base.py",
line 736, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File
"/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/db/models/base.py",
line 798, in _save_table
for f in non_pks] File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/db/models/base.py",
line 798, in
for f in non_pks] File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/django/db/models/fields/files.py", line 309, in pre_save
if file and not file._committed: File "/home/alexandr/sprutlabs_python/lib/python3.4/site-packages/PIL/Image.py",
line 632, in getattr
raise AttributeError(name) AttributeError: _committed


my model:

avatar = models.ImageField(
'Аватар',
blank=True,
null=True,
upload_to="user/avatar"
)

Answer

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()))