定制FileField中的上传文件名称实例
作者:jingxian 时间:2022-06-07 14:21:05
FileField中的upload_to属性可以设定上传文件的存储目录和名称,它可以是个字符串,也可以是个callable,比如一个方法。
当upload_to的值设为一个方法时,就可以对上传文件的名称进行修改了。方法需要两个参数,instance与filename,instance为此FileField所属的Model实例,filename为上传文件的名称。
举例:
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.id, filename)
class MyModel(models.Model):
upload = models.FileField(upload_to=user_directory_path)
当一个类定义了__call__方法时,也可以像func一样被调用,所以,upload_to的值也可以是一个定义了__call__方法的类。
比如,要根据上传时间为文件名加时间戳:
import hashlib
import os
import time
from django.utils.deconstruct import deconstructible
@deconstructible
class TimeStampFileName(object):
def __init__(self, path):
self.path = os.path.join(path, "%s%s")
def __call__(self, instance, filename):
extension = os.path.splitext(filename)[1]
data = "%s_%d"%(filename,int(time.time()))
file_hash = hashlib.sha1(data).hexdigest()
return self.path % (file_hash, extension)
Model中的FileField可以如下定义:
class MyModel(models.Model):
upload = models.FileField(upload_to=TimeStampFileName('media/'), )
来源:http://www.cnblogs.com/linxiyue/p/7412021.html
标签:上传文件名称,FileField
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
微信小程序-详解数据缓存
2024-04-19 09:49:34
![](https://img.aspxhome.com/file/2023/0/136130_0s.png)
PHP实现上传文件并存进数据库的方法
2023-07-03 21:35:14
python 调用pyautogui 实时获取鼠标的位置、移动鼠标的方法
2021-01-03 05:25:29
![](https://img.aspxhome.com/file/2023/9/101069_0s.jpg)
Win7环境下搭建Go开发环境(基于VSCode编辑器)
2024-04-30 09:59:04
![](https://img.aspxhome.com/file/2023/0/130920_0s.png)
对tf.reduce_sum tensorflow维度上的操作详解
2023-01-07 14:10:28
微信小程序实现计算器(含历史记录)
2024-04-17 10:30:20
![](https://img.aspxhome.com/file/2023/2/136262_0s.jpg)
了解WEB页面工具语言XML(六)展望
2008-09-05 17:19:00
Python中输入若干整数以逗号间隔实现统计每个整数出现次数
2021-10-27 22:20:04
![](https://img.aspxhome.com/file/2023/3/110003_0s.png)
matplotlib事件处理基础(事件绑定、事件属性)
2023-02-02 19:34:32
透明数据加密(TDE)库的备份和还原
2024-01-14 04:51:57
![](https://img.aspxhome.com/file/2023/7/94427_0s.png)
python 正则表达式贪婪模式与非贪婪模式原理、用法实例分析
2022-07-08 06:45:02
用Python写一个模拟qq聊天小程序的代码实例
2022-04-01 10:01:42
matplotlib给子图添加图例的方法
2023-05-02 03:21:28
![](https://img.aspxhome.com/file/2023/0/65460_0s.jpg)
微信小程序实现二维码生成器
2024-04-16 10:29:06
![](https://img.aspxhome.com/file/2023/1/136911_0s.png)
详解Python中的自定义密码验证
2021-06-05 00:38:59
mint-ui在vue中的使用示例
2023-07-02 16:52:17
![](https://img.aspxhome.com/file/2023/8/139808_0s.png)
Python lambda表达式filter、map、reduce函数用法解析
2022-03-30 03:52:31
回顾Javascript React基础
2023-07-13 00:57:00
php 模拟get_headers函数的代码示例
2023-09-09 06:16:36
mysql实现将字符串字段转为数字排序或比大小
2024-01-16 19:59:16
![](https://img.aspxhome.com/file/2023/2/99502_0s.png)