Django 6.1.3

12.5 Caching, signals, tasks, and files

Storage, FieldFile, and lazy file opening

Why does accessing a file field attribute on a model instance never open a file on disk until code reads bytes, and how does StorageHandler decouple models from local filesystems vs. object stores?

In the database, a Django FileField is just a "VARCHAR" storing a relative path string like "editions/2026-11-25.txt". Yet in Python, accessing that attribute gives you an object with FieldFile.url, FieldFile.size, FieldFile.open, FileProxyMixin.read, and FieldFile.save — without ever calling open() on disk or making an HTTP "GET" to S3 while you iterate a QuerySet of 500 models! Two clean abstractions make that work: StorageHandler and FileDescriptor + FieldFile.

StorageHandler and atomic FileSystemStorage._save

Open StorageHandler, backing django.core.files.storage.storages and the "settings.STORAGES" dictionary (containing "default" for user media and "staticfiles" for collected static assets). Indexing storages["default"] lazily imports and instantiates the configured Storage subclass once and caches it in "self._storages" — letting you switch a project from local disk (FileSystemStorage) to S3 or GCS by changing one dictionary entry in "STORAGES" without modifying a single model or migration!

Look closely at how FileSystemStorage._save writes bytes safely under concurrent requests:

  1. Path-traversal protection: FileSystemStorage.path runs safe_join(self.location, name), refusing any ".." path that would escape "MEDIA_ROOT" (SuspiciousFileOperation).
  2. Collision-safe atomic creation: Unless "allow_overwrite=True", FileSystemStorage._save opens the target path with low-level os.open flags os.O_WRONLY | os.O_CREAT | os.O_EXCL. Because O_CREAT | O_EXCL is atomic in the OS kernel, if two concurrent uploads both picked "editions/2026-11-25.txt", the second process receives FileExistsError, calls get_available_name to append a random 7-character suffix, and retries cleanly instead of silently clobbering the first upload!
  3. Exclusive lock & chunked streaming: While streaming "content.chunks()" to disk, Django acquires locks.LOCK_EX so another reader cannot observe a half-written file.

FileDescriptor, lazy FieldFile, and why Model.delete keeps the file

Now open FileDescriptor.__get__ (FileDescriptor.__get__, subclassing DeferredAttribute) and FieldFile:

Finally, understand one deliberate Django design decision that surprises almost everyone once: calling "instance.delete()" (or QuerySet.delete()) NEVER deletes the underlying file from storage! Django removed automatic file deletion on row delete intentionally for two rock-solid systems reasons:

  1. Transactions cannot roll back external storage: If you delete a model row inside django.db.transaction.atomic and a later step raises an exception, PostgreSQL rolls back the row cleanly — but if Django had already called "storage.delete()", the file on disk or S3 would be permanently gone, leaving a dangling broken row!
  2. Shared paths across rows and backups: Two rows (e.g., cloned drafts, fixtures, or database snapshots) can reference the same stored filename; deleting one row must never corrupt another row’s media.

If you want orphaned media cleaned up, trigger FieldFile.delete(save=False) inside django.db.transaction.on_commit — or sweep unreferenced blobs asynchronously via a scheduled task!

Watch storages, FileSystemStorage collision renaming, and FieldFile staying strictly unopened until FileProxyMixin.read executes live:

Recorded on Django 6.1.3 ch12-services script
5. StorageHandler, FileSystemStorage, and FieldFile lazy opening
  storages_aliases=['default', 'staticfiles'] saved_name='editions/2026-11-25.txt' collision_renamed=True
  fieldfile_lazy: closed_before=True opened_before_read=False opened_on_read=True bytes=16 url='/media/editions/2026-11-25.txt'

Now we close Part III with Django’s fifth horizontal service — how asgiref.local.Local manages per-thread and per-coroutine active languages and timezones, and what happens when a naive datetime.datetime hits a DateTimeField — in Thread-local languages and aware datetimes.