django - FileField:如何在名称和路径中使用带有空格的upload_to
问题描述
我有一个允许我上传文件的模型,但由于某种原因,自定义upload_to
函数中定义的空格在文件系统(或 s3)中被文件名和文件夹路径中的下划线替换。
有没有办法强制使用空格?
例如:文件“hello world.png”变为“hello_world.png”
ps:我知道使用空格是一种不好的做法,但这不是我的选择。
这是代码:
模型.py
one_file = models.FileField(
_('My label'),
null=True,
blank=True,
upload_to=one_file_name,
max_length=500,
#part for s3, using the local media doens't change anything
storage=PrivateMediaStorage(),
)
我的 upload_to 函数
def one_file_name(instance, filename):
extension = filename.split(".")[-1]
return f'folder name/subfolder name/{filename}.{extension}'
解决方案
文件名中的空格无论如何都会导致 url 中的错误,我认为这可能对您有所帮助,Django 调用 get_valid_filename() 以在保存时对文件名进行一些更改 - 针对您的情况,空格替换为下划线或您想要的任何内容。你可以在这里找到完整的文档。这是函数本身:
@keep_lazy_text
def get_valid_filename(s):
"""
Returns the given string converted to a string that can be used for a clean
filename. Specifically, leading and trailing spaces are removed; other
spaces are converted to underscores; and anything that is not a unicode
alphanumeric, dash, underscore, or dot, is removed.
>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_portrait_in_2004.jpg'
"""
s = force_text(s).strip().replace(' ', '_')
return re.sub(r'(?u)[^-\w.]', '', s)
推荐阅读
- css - CSS如何将项目分别向右或向左浮动到html方向?
- javascript - Vanilla Javascript,如何读取本地 JSON 文件
- javascript - 在 setTimeout() 的回调中获取计时器 ID?
- snowflake-cloud-data-platform - 雪花动态屏蔽屏蔽底层表:派生表未屏蔽,视图为空?
- c - 为什么 C 编译器允许从 uint16_t 静默转换为枚举类型?
- reactjs - 每张卡片的 AntD 表和输入字段
- python - 调用 PutObject 操作时发生错误 (404):未找到
- node.js - 如何解决 Nodemailer 中的 ENETUNREACH 错误
- image - VueJS 中的动态名称路由/动态路由匹配
- c# - 使用 JWT 非对称 RSA 密钥的 .Net Core 身份验证失败 - IDX10609:解密失败。未尝试任何键:令牌