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.2 Django 4.2 Django 3.2 django-storages

Django/Python Consulting

If you have a specific Django challenge or integration you'd like to solve, I'd be happy to help. Book a free 30-minute call to discuss your project, see if we're a good fit, and explore the best approach for your needs. After the call, you'll receive a tailored cost estimate based on what we discuss.