I have created a blog website in Django. I have posted multiple articles on the website. After deleting the article, the article gets deleted but the media files are not removed. I want to delete all media files which are not referred to the articles.
I know, I can create Django post-delete signal and delete media files from there. But it will applicable for only future use. I want to delete previous media files which are not in my database.
CodePudding user response:
first install this:
pip install django-cleanup
then, add this in settings file inside your installed_apps:
'django_cleanup.apps.CleanupConfig'
It will delete your media files.
CodePudding user response:
Just use this program to delete your unused media files.
This command deletes all media files from the MEDIA_ROOT directory which are no longer referenced by any of the models from installed_apps.
import os
from django.core.management.base import BaseCommand
from django.conf import settings
class Command(BaseCommand):
def handle(self, *args, **options):
physical_files = set()
db_files = set()
media_root = getattr(settings, 'MEDIA_ROOT', None)
if media_root is not None:
for relative_root, dirs, files in os.walk(media_root):
for file_ in files:
relative_file = os.path.join(os.path.relpath(relative_root,
media_root), file_)
physical_files.add(relative_file)
deletables = physical_files - db_files
if deletables:
for file_ in deletables:
os.remove(os.path.join(media_root, file_))