Django开发中经常会遇到上传文件后改名,以避免文件重名
其中上传文件后需要处理中文文件名或者重名,比较麻烦upload_to 可以设置成 upload_to="images/%Y/%m/%d"
也可通过编程动态设置(Django 2.2, Python3.7):
from uuid import uuid4
from datetime import datetime
def upload_article_cover(instance,filename):
ext = filename.split('.')[-1] #日期目录和 随机文件名
filename = f'{uuid4().hex}.{ext}'
now = datetime.now()
year,month,day = now.year ,now.month ,now.day
# instance可使用instance.user.id
return f"article/cover/{year}/{month}/{day}/{filename}"
class Article(models.Model):
width= models.IntegerField(null=True, blank=True)
height= models.IntegerField(null=True, blank=True)
cover = models.ImageField(upload_to=upload_article_cover, default="article/cover/default.png", width_field="width", height_field="height" )
网友评论