un1t/django-cleanup

Cleanup empty directories

mhamid3d opened this issue · 3 comments

I switched my project to use django-cleanup and it does things much better than my solution before, but one feature I don't have anymore is cleaning up empty directories after deleting a file.

This was my function for deleting File/Image:

def perform_media_delete(media_field):
    if os.path.isfile(media_field.path):
        os.remove(media_field.path)
        walk = list(os.walk(settings.MEDIA_ROOT))
        for path, _, _ in walk[::-1]:
            if len(os.listdir(path)) == 0:
                os.rmdir(path)
    else:
        return False

It removes all empty sub-directories relative to the MEDIA_ROOT location. This is useful when your upload_to path is something that follows the standards of using the first and second letter of the file name to build the directory:

/path/to/file/a/p/ap45bgfh3.png
--------------^ ^-^^

This feature may be undesirable for most, but is it something that can optional and disabled by default?

Have you tried using the signals?
https://github.com/un1t/django-cleanup#signals

from django_cleanup.signals import cleanup_post_delete

def directory_cleanup(**kwargs):
    ...cleanup empty directories...

cleanup_post_delete.connect(directory_cleanup)

Thanks @vinnyrose I think this is a more than sufficient solution.

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.