› Forums › Web Development › HarvardX: CS50W – CS50’s Web Programming with Python and JavaScript › CS50W – Lecture 3 – Django › What is default_storage in Django and How It Works
- This topic is empty.
-
AuthorPosts
-
March 25, 2026 at 10:52 pm #6280
In your earlier code, you used:
_, filenames = default_storage.listdir("entries")Now the key question is:
π€ What exactly is
default_storage?
π€ Where does it come from?
π€ How does it know where your files are?
π§© 1. What is
default_storage?default_storageis Djangoβs built-in file manager.π It is an instance of a storage class that handles:
- Reading files
- Writing files
- Listing files
- Deleting files
π Where is it defined?
You usually import it like this:
from django.core.files.storage import default_storageBehind the scenes, Django creates it based on your project settings.
βοΈ 2. How Django decides what
default_storageisDjango checks your settings:
DEFAULT_FILE_STORAGE = "django.core.files.storage.FileSystemStorage"π If you donβt change anything, it uses:
FileSystemStorage(local file system)
π§ 3. What is
FileSystemStorage?This is the default storage class that works with your local folders.
π Defined in:
django/core/files/storage.pyIt knows:
- Where your files are stored
- How to access them using OS functions
π 4. How it knows the “entries” folder
When you write:
default_storage.listdir("entries")Django internally converts
"entries"into a full path like:/path/to/your/project/entries/This depends on settings like:
MEDIA_ROOT BASE_DIR
π 5. What happens step-by-step
When this runs:
default_storage.listdir("entries")Django does:
- Convert
"entries"β full system path - Call OS:
os.listdir() - Separate:
- folders β directories list
- files β files list
- Return:
(directories, files)
π¦ 6. Example Flow
Your folder:
entries/ Python.md Django.md drafts/Internal working:
dirs, files = default_storage.listdir("entries")Result:
dirs = ["drafts"] files = ["Python.md", "Django.md"]
π 7. Why this abstraction is powerful
Because you can change storage without changing your code.
βοΈ Example: Switch to Cloud (AWS S3)
If you change settings:
DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"Now:
- Files are stored on AWS S3 βοΈ
- But your code stays SAME:
default_storage.listdir("entries")π Django handles everything internally
β‘ 8. Key Takeaways
default_storage= Djangoβs file handling system- Default = local filesystem (
FileSystemStorage) - It uses OS functions like:
os.listdir() os.path.isdir() - It always returns:
(directories, files)
π‘ Simple Mental Model
Think of
default_storageas:π¦ A universal file manager API
that works the same whether files are:- On your computer
- On a server
- On the cloud
π Bonus: Why CS50 uses this
In the Wiki project:
- Entries are stored as
.mdfiles default_storagelets you:- Read entries
- List entries
- Save entries
π Without worrying about file paths
-
AuthorPosts
- You must be logged in to reply to this topic.
