上犹电脑信息网我们一直在努力
您的位置:上犹电脑信息网 > 文件问题 > Django2.0 ImageField 和FileField上传文件后动态改名(实测)-文件更名

Django2.0 ImageField 和FileField上传文件后动态改名(实测)-文件更名

作者:上犹日期:

返回目录:文件问题

Django开发中经常会遇到上传文件后改名,以避免文件重名

其中上传文件后需要处理中文文件名或者重名,比较麻烦

Django2.0 ImageField 和FileField上传文件后动态改名(实测)

upload_to可以设置成 upload_to="images/%Y/%m/%d"

也可通过编程动态设置,现在有两种方式,均在Django 2.0, Python3.6 下完成测试,现在附上代码

  • 方法一(推荐):(models.py)

from uuid import uuid4
from datetime import datetime
def 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)

Django2.0 ImageField 和FileField上传文件后动态改名(实测)

注意url中的文件地址

方法二:(基于类)

from django.conf import settings
from django.utils.deconstruct import deconstructible
@deconstructible
class PathAndRename(object):
def __init__(self, sub_path):
self.path = sub_path
def __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)

相关阅读

关键词不能为空
极力推荐

电脑蓝屏_电脑怎么了_win7问题_win10问题_设置问题_文件问题_上犹电脑信息网

关于我们