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,530 points
2,142 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,880 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,780 points
591 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,140 points
3,702 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,540 points
7,516 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,540 points
220 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,880 points
1,016 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,880 points
461 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,880 points
3,549 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
131,678 views