How to delete old image when update ImageField?


Question

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?

1
30
2/23/2018 5:43:48 PM

Accepted Answer

You'll have to delete the old image manually.

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

os.remove(your_image_field.name)

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

16
2/23/2018 5:57:17 PM

Use django-cleanup

pip install django-cleanup

settings.py

INSTALLED_APPS = (
    ...
    'django_cleanup', # should go after your apps

)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon