What is a Django File Object?
I. What is a Django File Object?
Django abstracts a set of “file handling systems”. The core concept is:
django.core.files.File: The base class for all file-related classes in Django.
It provides a unified interface for:
- Reading
- Writing
- Iterating
- Saving to a Storage backend (local disk, OSS, S3, etc.)
Used with FileField / ImageField:
python
class MyModel(models.Model):
file = models.FileField(upload_to='files/')
This field does not store the file content in the database. It only stores the file path as a string.
The actual file saving is handled by:
django.core.files.File(or its subclasses likeContentFile)- A Storage system (default is local filesystem).
python
obj.file.save('result.txt', ContentFile('hello world'))
At this point, Django will:
- Write the
ContentFilecontent to local disk, OSS, S3, etc. - Write the saved path to the database field
file.
II. Which Django File Object to Use in Different Scenarios
Scenario 1: User Uploads a File (Common in Web/DRF)
python
def upload(request):
f = request.FILES['file'] # InMemoryUploadedFile or TemporaryUploadedFile
print(f.name, f.size, f.content_type)
Scenario 2: Dynamically Generate a File (e.g., CSV/JSON/Image) and Save to a FileField
python
from django.core.files.base import ContentFile
content = "name,age\nTom,18\nJerry,20"
obj.file.save("data.csv", ContentFile(content))
Scenario 3: Save a Locally Opened File (via Python open) to a FileField
python
from django.core.files import File
with open('local.txt', 'rb') as f:
obj.file.save('copy.txt', File(f))
III. Configuration for Different File Storage Backends
1. Local Storage: Saving to Server Disk
Django uses local disk storage by default. The class used is:
python
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
In settings.py:
python
import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Actual file save path MEDIA_URL = '/media/' # Browser access prefix
Model configuration:
python
class MyModel(models.Model):
file = models.FileField(upload_to='uploads/')
Finally, executing:
python
obj.file.save('a.txt', ContentFile('hello'))
Actual Effect:
- File is saved to:
MEDIA_ROOT / uploads / a.txt- Example:
/project_root/media/uploads/a.txt
- Example:
- The database field stores only the relative path:
uploads/a.txt - Browser access URL is:
MEDIA_URL + 'uploads/a.txt'→/media/uploads/a.txt
To access files via URL, add a static route in urls.py:
python
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... your other URLs
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
2. Cloud Storage: S3/OSS/COS/BOS, etc.
1) Use existing libraries (e.g., django-storages with S3). Installation required:
bash
pip install django-storages boto3
settings.py configuration:
python
INSTALLED_APPS = [
# ...
'storages',
]
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_ACCESS_KEY_ID = 'Your_Key'
AWS_SECRET_ACCESS_KEY = 'Your_Secret'
AWS_STORAGE_BUCKET_NAME = 'Your_Bucket_Name'
AWS_S3_ENDPOINT_URL = 'https://s3.amazonaws.com' # For other cloud providers, use their S3-compatible endpoint
MEDIA_URL = 'https://your-bucket-domain/' # Access URL prefix
Model remains unchanged:
python
class MyModel(models.Model):
file = models.FileField(upload_to='files/')
Business logic code:
python
obj.file.save('a.txt', ContentFile('hello cloud'))
Django will:
- Upload the file content to your bucket via S3 API:
files/a.txt - The database field still stores
files/a.txt - Page access URL becomes:
MEDIA_URL + 'files/a.txt', e.g.,https://your-bucket.xxx.com/files/a.txt
Related articles