美文网首页
django 图片保存时修改图片名称

django 图片保存时修改图片名称

作者: 青铜搬砖工 | 来源:发表于2019-03-11 17:03 被阅读0次
    import os
    from uuid import uuid4
    def path_and_rename(path):
        def wrapper(instance, filename):
            ext = filename.split('.')[-1]
            # get filename
            if instance.pk:
                filename = '{}.{}'.format(instance.pk, ext)
            else:
                # set filename as random string
                filename = '{}.{}'.format(uuid4().hex, ext)
            # return the whole path to the file
            return os.path.join(path, filename)
        return wrapper
    
    class Ablum(models.Model):
        user = models.ForeignKey(ProfileUser, related_name="ablum_created", on_delete=models.CASCADE,blank=True)
        title = models.TextField(max_length=1024)
        thumb = ProcessedImageField(upload_to=path_and_rename("images/%Y/%m/%d"), processors=[ResizeToFit(300)], format='JPEG',
                                    options={'quality': 90},blank=True)
    

    model.save()的时候会触发upload_to,然后给一个新名称

    相关文章

      网友评论

          本文标题:django 图片保存时修改图片名称

          本文链接:https://www.haomeiwen.com/subject/kfibpqtx.html