[Django]-FileField: How to use upload_to with a whitespace in the name and path

6👍

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)

Leave a comment