Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove previous image file when ImageValue change #34

Open
rolexCoder opened this issue Jun 3, 2016 · 2 comments
Open

Remove previous image file when ImageValue change #34

rolexCoder opened this issue Jun 3, 2016 · 2 comments

Comments

@rolexCoder
Copy link

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.

@zlorf
Copy link
Owner

zlorf commented Jun 3, 2016

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

@rolexCoder
Copy link
Author

You are right!

Next time I will make a Pull Request for sure!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants