django-versatileimagefield
django-versatileimagefield copied to clipboard
Delete file on changing file
In my model I have a code that delete the original file when is changed to not have multiple useless files around. The problem it is to do the same for the thumbnails generated.
@deconstructible
class PathAndRename:
"""
A callable class that generates unique file paths for uploads.
This class is designed to be used as the upload_to parameter in Django model fields.
It generates a unique filename using UUID4 while preserving the original file extension,
and places the file in the specified subdirectory.
The @deconstructible decorator makes this class serializable for Django migrations,
which is essential for avoiding migration generation issues.
Note: No slash for the path!
Args:
sub_path (str): The subdirectory path where files should be stored
Example:
>>> uploader = PathAndRename("product_logos")
>>> uploader(instance, "logo.png")
'product_logos/abc123def456.png'
"""
def __init__(self, sub_path):
self.path = sub_path
def __call__(self, instance, filename):
ext = filename.split(".")[-1]
filename = f"{uuid4().hex}.{ext}"
return os.path.join(self.path, filename)
path_and_rename = PathAndRename("product_logos")
logo = VersatileImageField(
upload_to=path_and_rename,
)