Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete old image when update ImageField?

I'm using Django to create a stock photo site, I have an ImageField in my model, the problem is that when the user updates the image field, the original image file isn't deleted from the hard disk.

How can I delete the old images after an update?

like image 498
eos87 Avatar asked May 20 '10 23:05

eos87


4 Answers

Use django-cleanup

pip install django-cleanup

settings.py

INSTALLED_APPS = (
    ...
    'django_cleanup.apps.CleanupConfig', # should be placed after your apps

)
like image 104
un1t Avatar answered Oct 10 '22 17:10

un1t


You'll have to delete the old image manually.

The absolute path to the image is stored in your_image_field.path. So you'd do something like:

os.remove(your_image_field.path)

But, as a convenience, you can use the associated FieldFile object, which gives easy access to the underlying file, as well as providing a few convenience methods. See http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield-and-fieldfile

like image 29
Chris Lawlor Avatar answered Oct 10 '22 18:10

Chris Lawlor


Use this custom save method in your model:

def save(self, *args, **kwargs):
    try:
        this = MyModelName.objects.get(id=self.id)
        if this.MyImageFieldName != self.MyImageFieldName:
            this.MyImageFieldName.delete()
    except: pass
    super(MyModelName, self).save(*args, **kwargs)

It works for me on my site. This problem was bothering me as well and I didn't want to make a cleanup script instead over good bookkeeping in the first place. Let me know if there are any problems with it.

like image 21
metamemetics Avatar answered Oct 10 '22 18:10

metamemetics


Before updating the model instance, you can use the delete method of FileField object. For example, if the FileField or ImageField is named as photo and your model instance is profile, then the following will remove the file from disk

profile.photo.delete(False)

For more clarification, here is the django doc

https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.fields.files.FieldFile.delete

like image 18
Nayan Avatar answered Oct 10 '22 18:10

Nayan