How to delete old image when update ImageField

0 votes
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?
Jun 29, 2020 in Python by kartik
• 37,520 points
4,674 views

1 answer to this question.

0 votes

Hello @kartik,

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

Hope it helps!!

Thank You!!

answered Jun 29, 2020 by Niroj
• 82,840 points

Related Questions In Python

+1 vote
2 answers

How to resize the image canvas to maintain a square aspect ratio

down voteacceptedUsing OpenCVYou can use resize() in OpenCV to ...READ MORE

answered Apr 4, 2018 in Python by charlie_brown
• 7,720 points

edited Jul 11, 2023 by Khan Sarfaraz 1,644 views
0 votes
1 answer

How to resize image canvas to maintain square aspect ratio in Python, OpenCv

Building on Alexander-Reynolds answer above, here is ...READ MORE

answered Sep 4, 2018 in Python by Priyaj
• 58,020 points
5,192 views
0 votes
1 answer

How to save Numpy array as image in python?

If you have matplotlib, you can do: import ...READ MORE

answered Nov 16, 2018 in Python by Nymeria
• 3,560 points
8,946 views
0 votes
1 answer

How to get textual output when using exceptions in Python?

Hi, the answer is pretty simple.  Without the ...READ MORE

answered Jan 17, 2019 in Python by Nymeria
• 3,560 points
969 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
2,437 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,840 points
1,555 views
0 votes
1 answer

How to show Image from Imagefield Django Admin ?

Hello @kartik, In your model class add a ...READ MORE

answered Aug 3, 2020 in Python by Niroj
• 82,840 points
5,590 views
+1 vote
3 answers

How to change/update cell value in Python Pandas dataframe?

You can use the at() method to ...READ MORE

answered Apr 8, 2019 in Python by Kunal
147,342 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP