import os from django.core.management import BaseCommand from django.db import transaction from boards.models.image import IMAGES_DIRECTORY, PostImage, IMAGE_THUMB_SIZE from neboard.settings import MEDIA_ROOT __author__ = 'neko259' class Command(BaseCommand): help = 'Remove image files whose models were deleted' @transaction.atomic def handle(self, *args, **options): count = 0 thumb_prefix = '.{}x{}'.format(*IMAGE_THUMB_SIZE) model_files = os.listdir(MEDIA_ROOT + IMAGES_DIRECTORY) for file in model_files: image_name = file if thumb_prefix not in file else file.replace(thumb_prefix, '') found = PostImage.objects.filter(image=IMAGES_DIRECTORY + image_name).exists() if not found: print('Missing {}'.format(image_name)) os.remove(MEDIA_ROOT + IMAGES_DIRECTORY + file) count += 1 print('Deleted {} image files.'.format(count))