Django开发中经常会遇到上传文件后改名,以避免文件重名
其中上传文件后需要处理中文文件名或者重名,比较麻烦
upload_to可以设置成 upload_to="images/%Y/%m/%d"
也可通过编程动态设置,现在有两种方式,均在Django 2.0, Python3.6 下完成测试,现在附上代码
方法一(推荐):(models.py)
from uuid import uuid4from datetime import datetimedef upload_article_cover(instance,filename): ext = filename.split(.)[-1] #日期目录和 随机文件名 filename = {}.{}.format(uuid4().hex, ext) year = datetime.now().year month =datetime.now().month day = datetime.now().day #instance 可使用instance.user.id return "article/cover/{0}/{1}/{2}/{3}".format(year,month,day,filename)class Article(models.Model): cover = models.ImageField(upload_to=upload_article_cover, verbose_name="封面", default="article/cover/default.png", width_field="width", height_field="height" ) width= models.IntegerField(null=True,blank=True) height= models.IntegerField(null=True,blank=True)
注意url中的文件地址
方法二:(基于类)
from django.conf import settingsfrom django.utils.deconstruct import deconstructible@deconstructibleclass PathAndRename(object):def __init__(self, sub_path):self.path = sub_pathdef __call__(self, instance, filename):ext = filename.split(.)[-1]# 设置文件名随机数filename = {}.{}.format(uuid4().hex, ext)# 返回整个文件全路径return os.path.join(self.path, filename)path_and_rename = PathAndRename(os.path.join(settings.MEDIA_ROOT,"avatars"))image = models.ImageField(upload_to=path_and_rename,width_field="width",height_field="height",null=True,blank=True)