Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileField: How to use upload_to with a whitespace in the name and path

I have a model that allow me to upload a file, but for some reason the whitespace defined in the custom upload_to function get replaced by underscore in the file system(or in s3) for both the filename and the folder path.

Is there a way to enforce the use of whitespace?

eg: The file "hello world.png" become "hello_world.png"

ps: I know this is a bad practice to use whitespace, but it's not my choice .

Here is the code:

models.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(),
)

my upload_to function

def one_file_name(instance, filename):
    extension = filename.split(".")[-1]
    return f'folder name/subfolder name/{filename}.{extension}'
like image 525
Ben Boyer Avatar asked Jan 26 '26 15:01

Ben Boyer


1 Answers

space in file name cuase an error in url anyway I think this could help to you ,Django calls get_valid_filename() to make some alterations to filenames when saved - specific to your case, spaces are replaced with underscores or anything you want. You can find the full docs here. Here's the function itself:

@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)
like image 196
hassanzadeh.sd Avatar answered Jan 28 '26 22:01

hassanzadeh.sd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!