无法将图像保存到django模型

时间:2016-07-05 22:19:53

标签: python django python-3.x django-models pillow

我尝试在保存之前调整图片大小:

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
        )

但是我在保存时收到以下错误:

> 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 <listcomp>
>     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

我的模特:

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

1 个答案:

答案 0 :(得分:1)

您不能像这样直接将PIL图像分配给ImageField。您需要一些解决方法:

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