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:
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(),
)
def one_file_name(instance, filename):
extension = filename.split(".")[-1]
return f'folder name/subfolder name/{filename}.{extension}'
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With