无法从Django中的Model方法保存头像字段

时间:2016-04-27 15:54:04

标签: django django-models amazon-s3 django-uploads

我正在关注this教程上传(到S3亚马逊)并使用Django操作图像。 我被困在某个地方,因为我能够上传文件,但每当调用应该创建拇指的方法时,我认为错过了一些东西。

这是代码:

def upload_avatar_to(instance, filename):
        import os
        from django.utils.timezone import now
        filename_base, filename_ext = os.path.splitext(filename)
        return 'media/images/avatars/%s%s' % (
            now().strftime("%Y%m%d%H%M%S"),
            filename_ext.lower(),
        )

class CustomUser(AbstractBaseUser, PermissionsMixin):
    avatar = models.ImageField('profile picture', upload_to=upload_avatar_to, null=True, blank=True)

    def save(self, *args, **kwargs):
        super(CustomUser, self).save(*args, **kwargs)
        self.create_avatar_thumb()

    def create_avatar_thumb(self):
        import os
        from django.core.files.storage import default_storage as storage
        if not self.avatar:
            return ""
        file_path = self.avatar.name
        filename_base, filename_ext = os.path.splitext(file_path)
        thumb_file_path = "%s_thumb.jpg" % filename_base
        if storage.exists(thumb_file_path):
            return "exists"
        try:
            f = storage.open(file_path, 'r')
            image = Image.open(f)
            width, height = image.size

            if width > height:
                delta = width - height
                left = int(delta/2)
                upper = 0
                right = height + left
                lower = height
            else:
                delta = height - width
                left = 0
                upper = int(delta/2)
                right = width
                lower = width + upper

            image = image.crop((left, upper, right, lower))
            image = image.resize((250, 250), Image.ANTIALIAS)

            f_thumb = storage.open(thumb_file_path, "w")
            image.save(f_thumb, "JPEG")
            f_thumb.close()
            return "success"
        except:
            return "error"

    def get_avatar_thumb_url(self):
        import os
        from django.core.files.storage import default_storage as storage
        if not self.avatar:
            return ""
        file_path = self.avatar.name
        filename_base, filename_ext = os.path.splitext(file_path)
        thumb_file_path = "%s_thumb.jpg" % filename_base
        if storage.exists(thumb_file_path):
            return storage.url(thumb_file_path)
        return ""

似乎一切都还可以,但代码应该有问题 我上传了图片,没有发现任何错误,但是:

  1. 图片未调整大小
  2. 没有创建“avatar-name_thumb.jpg”并将其上传到存储桶
  3. 我该怎么办?

0 个答案:

没有答案