5
I actually take a closer look with your help and a found something
So basically I have to do something like:
from django.core.files.storage import FileSystemStorage
fss = FileSystemStorage()
filepath = fss.get_available_name(filepath)
Thank you all
PS: If you are interesting, the comment from django.core.file.storage.FileSystemStorage._save says:
Thereβs a potential race condition between get_available_name and
saving the file; itβs possible that two threads might return the
same name, at which point all sorts of fun happens. So we need to
try to create the file, but if it already exists we have to go back
to get_available_name() and try again.
2
If you see the implementation of class django.core.files.storage.Storage
you will know how Django 1.6
manages the file names.
Look into the save
method of this class. In this the line
name = self.get_available_name(name)
is doing the trick.
This is the default implementation of getting the new file name before saving the file. If you want to write your own version (like the file should be overridden) then consider writing your own custom storage system
- [Django]-How do I filter API results by a related model attribute using Tastypie?
- [Django]-Django-tables2 exclude & field not working
1
Actually, you were on the right track.
From the docs,
Internally, Django uses a django.core.files.File instance any time it
needs to represent a file.
And also,
Behind the scenes, Django delegates decisions about how and where to
store files to a file storage system
Which means that, when the file is uploaded, using the default storage (FileSystemStorage), Django delegates the naming (or the available name), behind the scene, for the file to the storage, which then uses: get_available_name(name)
.
So, If you want to change the way files are named when uploaded, you need to add a custom file storage, which would basically only override get_available_name
. The documentation on the matter is here.
- [Django]-ModelForm and error_css_class
- [Django]-Crispy-forms InlineRadios don't show my model state
- [Django]-NameError: name 'RegexValidator' is not defined