django模型中ImageField的缩略图,覆盖保存

时间:2017-03-24 09:48:50

标签: python django python-imaging-library

我正在尝试从ImageField创建缩略图并将其保存到我的模型中。我将此作为参考:http://www.yilmazhuseyin.com/blog/dev/create-thumbnails-imagefield-django/

文件创建正确,我没有错误,但字段未保存在模型中。 我想我可以用save方法搞砸了。我做错了什么?

这是我的代码:

def get_avatar_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'avatars/{0}/{1}'.format(instance.id, filename)


class User(AbstractUser):
    # First Name and Last Name do not cover name patterns
    # around the globe.
    name = models.CharField(_('Name of User'), blank=True, max_length=255)
    avatar = models.ImageField(upload_to=get_avatar_path, blank=True)
    small_avatar = models.ImageField(upload_to=get_avatar_path,
                                     blank=True)

    def create_thumbnail(self):
        # If there is no image associated with this.
        # do not create thumbnail
        if not self.avatar:
            return

        # Set our max thumbnail size in a tuple (max width, max height)
        THUMBNAIL_SIZE = (200, 200)

        DJANGO_TYPE = self.avatar.file.content_type
        print DJANGO_TYPE

        if DJANGO_TYPE == 'image/jpeg':
            PIL_TYPE = 'jpeg'
            FILE_EXTENSION = 'jpg'
        elif DJANGO_TYPE == 'image/png':
            PIL_TYPE = 'png'
            FILE_EXTENSION = 'png'
        elif DJANGO_TYPE == 'image/gif':
            PIL_TYPE = 'gif'
            FILE_EXTENSION = 'gif'

        # Open original photo which we want to thumbnail using PIL's Image
        image = Image.open(StringIO(self.avatar.read()))

        # use our PIL Image object to create the thumbnail, which already
        image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)

        # Save the thumbnail
        temp_handle = StringIO()
        image.save(temp_handle, PIL_TYPE)
        temp_handle.seek(0)

        # Save image to a SimpleUploadedFile which can be saved into ImageField
        print os.path.split(self.avatar.name)[-1]
        suf = SimpleUploadedFile(os.path.split(self.avatar.name)[-1],
                                 temp_handle.read(), content_type=DJANGO_TYPE)
        # Save SimpleUploadedFile into image field
        print os.path.splitext(suf.name)[0]
        self.small_avatar.save(
            '%s_thumbnail.%s' % (os.path.splitext(suf.name)[0], FILE_EXTENSION),
            suf, save=False)

    def save(self, *args, **kwargs):
        self.create_thumbnail()
        super(User, self).save()

1 个答案:

答案 0 :(得分:0)

感谢您的反馈。对不起新手问题,我是初学者。 问题似乎通过使缓存无效,重新启动IDE和服务来解决。 在我看来,上面的代码应该被保留,因为网络上的一些解决方案已经过时了。