djangoimagefieldfilefield

Delete Django ImageField and FileField records whose files are not found on the server


I've recently lost some files in my media folder, and I want to delete the image field/FileField objects whose files have been removed, across all models of my application.

I've tried django-cleanup, but it appears to be doing the inverse operation, i.e. deleting files on the server whose objects have been removed from the database.


Solution

  • You can write a management command for this, here is a way how to handle this

    Class cleanup(BaseCommand):
        def handle(self,options):
             for obj in Files.objects.all():
                 if os.path.exists(settings.MEDIA_DIR+ obj.filename): continue
                 obj.delete()