# Imports
from django.core.files.storage import FileSystemStorage
# Exports
__all__ = (
"OverwriteStorage",
)
# Classes
[docs]class OverwriteStorage(FileSystemStorage):
"""Upload a file, overwriting an existing file."""
# TODO: See Django file_storage tests for guidance on how to test OverwriteStorage
# https://github.com/django/django/blob/master/tests/file_storage/tests.py
# See also: https://stackoverflow.com/a/11170472/241720
[docs] def get_available_name(self, name, max_length=None):
"""Since the purpose of the storage class is to overwrite, the name is returned as is."""
return name
[docs] def save(self, name, content, max_length=None):
"""Delete the existing file if it exists before saving the new file."""
if self.exists(name):
self.delete(name)
return super().save(name, content, max_length=max_length)