1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import os
from django.conf import settings
from django.core.files.storage import FileSystemStorage
class OverwriteStorage(FileSystemStorage):
def get_available_name(self, name):
"""
Returns a filename that's free on the target storage system, and
available for new content to be written to.
"""
# If the filename already exists, remove it as if it was a true file system
if self.exists(name):
os.remove(os.path.join(settings.MEDIA_ROOT, name))
return name
|
More like this
- Unique FileFiled or FileFiled with custom validation and overwriting files on update by evilclay 2 years, 4 months ago
- Database file storage by powerfox 4 years, 3 months ago
- Overwriting file storage by wolever 2 years, 8 months ago
- Whitelisted overwriting FileSystemStorage by nickma_at 1 year, 9 months ago
- ImageWithThumbsField by zenx 4 years, 4 months ago
Comments
Sweet... simple and effective. One small comment... it might be slightly better to change the deletion to instead be:
self.delete(name)as FileSystemStorage provides the method.
#
There's another idea for fixing it in bug 4339 (overriding
_saveinstead ofget_available_name).#
For those confused how to implement this, put the function in your models.py file and use
storage=OverwriteStorage()on your FileField declarations.For example,
powerpoint_file = models.FileField(upload_to="songs/", storage=OverwriteStorage(), blank=True)#