首页 > 解决方案 > 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}'

标签: djangodjango-models

解决方案


文件名中的空格无论如何都会导致 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)

推荐阅读