django-dbsettings
django-dbsettings copied to clipboard
Remove previous image file when ImageValue change
Hi,
When the value of an ImageValue field changes, the previous image file is preserved in the file system.
It would be a good improvement to remove the previous file just after the new one is uploaded.
To do this I inserted the following code in line 320 of value.py:
# Remove previous image file:
current_value = self.__get__(value)
current_filename = pjoin(settings.MEDIA_ROOT, current_value)
if os.path.isfile(current_filename):
os.remove(current_filename)
As a reference, the complete get_db_prep_save()
function must look like this:
def get_db_prep_save(self, value):
"Returns a value suitable for storage into a CharField"
if not value:
return None
hashed_name = md5(six.text_type(time.time()).encode()).hexdigest() + value.name[-4:]
image_path = pjoin(self._upload_to, hashed_name)
dest_name = pjoin(settings.MEDIA_ROOT, image_path)
directory = pjoin(settings.MEDIA_ROOT, self._upload_to)
if not os.path.exists(directory):
os.makedirs(directory)
with open(dest_name, 'wb+') as dest_file:
for chunk in value.chunks():
dest_file.write(chunk)
# Remove previous image file:
current_value = self.__get__(value)
current_filename = pjoin(settings.MEDIA_ROOT, current_value)
if os.path.isfile(current_filename):
os.remove(current_filename)
return six.text_type(image_path)
I tested this on Django 1.9 With Python 3.5 and as you can see the code will work on any version of Python.
Thanks for the idea. I wonder why didn't you make a Pull Request. ;)
You are right!
Next time I will make a Pull Request for sure!