Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django delete unused media files

I have a django project in which the admins are able to upload media. As items sell, they are deleted from the site, thus removing their entry in the MySQL database. The images associated with the item, however, remain on the file system. This isn't neccessarily bad behavior - I don't mind keeping files around in case a deletion was an accident. The problem I forsee is two years from now, when storage space is limited because of a media folder bloated with old product images.

Does anyone know of a systematic/programmatic way to sort through ALL the images and compare them to the relevant MySQL fields, deleting any image which DOESN'T have a match from the filesystem? In the perfect world I'm imagining a button in the django-admin like "Clean-up unused media" which executes a python script capable of this behavior. I'll be sharing whatever my eventual solution is here, but what I'm looking for right now is anyone who has ideas, knows resources, or has done this at some point themselves.

like image 680
Fabrizio A Avatar asked Feb 21 '14 17:02

Fabrizio A


People also ask

What is Django-cleanup?

The django-cleanup app automatically deletes files for FileField , ImageField and subclasses. When a FileField 's value is changed and the model is saved, the old file is deleted. When a model that has a FileField is deleted, the file is also deleted.


2 Answers

Try django-cleanup, it automatically invokes delete method on FileField when you remove model.

pip install django-cleanup 

settings.py

INSTALLED_APPS = (      ...     'django_cleanup.apps.CleanupConfig', # should go after your apps ) 
like image 51
un1t Avatar answered Oct 14 '22 05:10

un1t


django-unused-media will help you to clean old unused media by management command.

Very useful when you just started to use django-cleanup and already have files which needs to be deleted. Or if you have thumbnails which needs to be deleted from media directory.

like image 26
Andrey Kolpakov Avatar answered Oct 14 '22 05:10

Andrey Kolpakov