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

2019-03-11  本文已影响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,然后给一个新名称

上一篇下一篇

猜你喜欢

热点阅读