django-dbsettings icon indicating copy to clipboard operation
django-dbsettings copied to clipboard

Remove previous image file when ImageValue change

Open rolexCoder opened this issue 8 years ago • 2 comments

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.

rolexCoder avatar Jun 03 '16 14:06 rolexCoder

Thanks for the idea. I wonder why didn't you make a Pull Request. ;)

zlorf avatar Jun 03 '16 14:06 zlorf

You are right!

Next time I will make a Pull Request for sure!

rolexCoder avatar Jun 03 '16 15:06 rolexCoder