› Forums › Web Development › HarvardX: CS50W – CS50’s Web Programming with Python and JavaScript › CS50W – Lecture 3 – Django › How Django Reads Files Using default_storage.open()
- This topic is empty.
-
AuthorPosts
-
March 25, 2026 at 11:03 pm #6281
Now you already understand:
listdir()β gives file namesdefault_storageβ manages files
Next big question:
π€ How does Django read the content of
Python.md?
π§© 1. Real Context (CS50 Wiki)
You donβt just list entries β you also open and display them.
Typical function:
def get_entry(title): try: with default_storage.open(f"entries/{title}.md") as f: return f.read().decode("utf-8") except FileNotFoundError: return None
π§ What this function does
π βOpen the file β read its content β return it as textβ
π Step-by-step breakdown
1. Opening the file
default_storage.open(f"entries/{title}.md")This tells Django:
βGo to storage and open this fileβ
2. What Django does internally
Behind the scenes:
open("/full/path/to/entries/Python.md", "rb")"rb"β read in binary mode- Works for all file types
3. Reading the content
f.read()π Returns:
b"# Python\nPython is a programming language..."β οΈ This is bytes, not normal text
4. Converting bytes to string
.decode("utf-8")π Converts:
b"# Python..." β "# Python..."
5. Handling missing files
except FileNotFoundError: return Noneπ If file doesnβt exist:
- No crash β
- Returns
Noneβ
π Example
File:
entries/Python.md# Python Python is a high-level programming language.Output of function:
"# Python\nPython is a high-level programming language."
π How this connects to your app
Flow:
list_entries()β shows titles- User clicks “Python”
get_entry("Python")runs- Content is returned
- You render it on webpage
βοΈ Internal Django Logic (Simplified)
Inside
default_storage.open():def open(self, name, mode='rb'): return File(open(full_path, mode))π It wraps Pythonβs built-in
open()
β‘ Important Concepts You Just Learned
- File reading in Django
- Binary vs text (
bytes β string) - Safe file handling (
try/except) - Storage abstraction (local vs cloud)
π‘ Simple Mental Model
Think of it like:
π βOpen book β read pages β translate into readable textβ
π Bonus: Why
.decode("utf-8")mattersWithout it:
b"# Python\n..."With it:
"# Python\n..."π Required for rendering in HTML/templates
-
AuthorPosts
- You must be logged in to reply to this topic.
