About Deleting a Directory and its Files from Media

Use the following function to delete a directory under media root:

def delete_directory(directory_path):
    import os
    from django.core.files.storage import default_storage

    directories, files = default_storage.listdir(directory_path)

    for item in directories:
        item_path = os.path.join(directory_path, item)
        if default_storage.exists(item_path):
            # Recursively delete subdirectories
            delete_directory(item_path)  

    for item in files:
        item_path = os.path.join(directory_path, item)
        if default_storage.exists(item_path):
            # Delete files
            default_storage.delete(item_path)

    if default_storage.exists(directory_path):
        # Finally, delete the empty directory
        default_storage.delete(directory_path)

Then you would call it like so:

delete_directory(f"profiles/{username}")

It works not only with a simple file system, but also with Amazon S3, DigitalOcean Spaces, or a similar remote storage when using django-storages.

Tips and Tricks Programming Architecture Development Django 5.x Django 4.2 Django 3.2 django-storages