Django FileField:如何使用upload_to在名称和路径中使用空格

Django FileField:如何使用upload_to在名称和路径中使用空格,django,django-models,Django,Django Models,我有一个允许上传文件的模型,但由于某种原因,在文件系统(或s3)中,文件名和文件夹路径的自定义upload_to函数中定义的空白被下划线替换 有没有办法强制使用空格? 例如: 文件“hello world.png”变成“hello\u world.png” ps:我知道使用空白是一种不好的做法,但这不是我的选择 代码如下: models.py 我的上传功能 文件名中的空格由于url中出现错误,我认为这可能会对您有所帮助,Django调用get_valid_filename()在保存时对文件名进行

我有一个允许上传文件的模型,但由于某种原因,在文件系统(或s3)中,文件名和文件夹路径的自定义
upload_to
函数中定义的空白被下划线替换

有没有办法强制使用空格?

例如: 文件“hello world.png”变成“hello\u world.png”

ps:我知道使用空白是一种不好的做法,但这不是我的选择

代码如下:

models.py 我的上传功能
文件名中的空格由于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)

请注意,
upload\u to
指定要上载文件的目录,而不是最终文件名。因此,根据您的设置,文件将另存为文件夹/子文件夹/文件名.ext/filename\u 45ef8a.extwhitespaces,文件名中的空格将导致url中出现错误。如果您需要不带空格的名称,请将其保存在另一个model attr中。这是我现在尝试查找2小时的函数!我会挖一点,看看我能不能让它工作。
def one_file_name(instance, filename):
    extension = filename.split(".")[-1]
    return f'folder name/subfolder name/{filename}.{extension}'
@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)