Member-only story
🧹 Clean Up Django’s media/ Folder: Find and Delete Unused Files Safely
In Django projects, the media/ folder often becomes a digital junk drawer. Files like old profile pictures, unused uploads, or test files can sit around long after their related model entries are gone.
Over time, this can consume valuable disk space and clutter your deployment.
In this guide, you’ll learn how to safely detect and delete unused media files in Django using a custom management command — organized inside a dedicated app called media_management.
đźš© Why Django Leaves Media Files Behind
When you delete a model instance in Django, it removes the database row — but not the file on disk.
user = User.objects.get(id=1)
user.delete() # Deletes user, but not the profile_image fileUnless you handle this manually or with signals, that file remains in your media folder forever.
🎯 What We’ll Build
We’ll create a custom management command to:
- âś… Scan all files in your
MEDIA_ROOT - âś… Detect which files are still referenced in the database
- âś… List files that are unreferenced (unused)
- 🗑️ (Optionally) Delete unused files when confirmed
