Hi,
For my application I created a custom ImageField (code below) as I need to automatically generate a few different sets of thumbnails. I read the posts on the requests for Django to delete old images when uploading, and was blown away to see the request for that feature turned down. I still don't know why anyone would want the old images that you have zero access to (from ui) laying around when you change to a new one.
Anyway, this is my attempt to solve that oversight for my current application. First I tried calling the ImageField.delete if on an instance of the old image however that deletes the old and doesn't save the updated new image. So I created a new method that only removes. (This code is currently working how I need it to work)
On to the code:
fields.py
class ProfileThumbnailImageFieldFile(ImageFieldFile):
# code left out for creating the thumbnails
def remove_old_files(self):
if os.path.exists(self.path):
os.remove(self.path)
if os.path.exists(self.thumb_path_64x64):
os.remove(self.thumb_path_64x64)
class ThumbnailImageField(ImageField):
attr_class = ThumbnailImageFieldFile # This class definition left out and is overridden for this example in __init__ when creating the field
models.py
class CustomUser(AbstractBaseUser):
picture = ThumbnailImageField(upload_to='upload_path', attr_class=ProfileThumbnailImageFieldFile)
def __init__(self, *args, **kwargs):
super(CustomUser, self).__init__(*args, **kwargs)
# Store a reference of the original picture to allow for removing it alter if updated.
if self.picture:
self._original_picture = self.picture
else:
self._original_picture = None
def save(self, *args, **kwargs):
if self._original_picture:
if self.picture and self.picture != self._original_picture:
self._original_picture.remove_old_files()
super(CustomUser, self).save(*args, **kwargs)
What has been some other ways to solve this kind of problem?