Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Control over filenames #29

Open
alejasper opened this issue Feb 22, 2019 · 3 comments
Open

Control over filenames #29

alejasper opened this issue Feb 22, 2019 · 3 comments

Comments

@alejasper
Copy link

At present, if a file already exists within the directory with the same name, the new file is renamed. Is there any way to preserve the orginal filename either by deleting the old existing file, renaming the existing file first, sending a sub directory or some other way?
Kind regards.

@vdboor
Copy link
Member

vdboor commented Feb 27, 2019

For the S3 storage there is an AWS_PRIVATE_S3_FILE_OVERWRITE setting. The standard Django FileSystemStorage doesn't have such option afaik.

@jedie
Copy link

jedie commented Apr 10, 2019

I recently implemented OverwriteFileSystemStorage backend for something like this with optional backup functionality. Available in my django-tools project:

https://github.com/jedie/django-tools#overwritefilesystemstorage

@Chrescht
Copy link

I ended up using a function for upload_to in the model definition:

def get_file_path_photo(instance, filename):
    date_now = datetime.now().strftime('%Y-%m-%d_%H.%M.%S%')
    ext = filename.split('.')[-1]
    filename = f"photo_{instance.somefield}_{date_now}.{ext}"
    return os.path.join('photos', filename)

Then, when defining your FileField/ImageField, specify get_file_path as the upload_to value.

class myModel(..):
    photo = models.FileField(upload_to=get_file_path_photo, ..)

instance.somefield has to exist in the database before the file is saved
The name should be unique, in this case the instance - date combination is taking care of that bit.

source: stackoverflow: enforce unique upload file names using django

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants