Full answer
Flow: the browser sends multipart/form-data with enctype; Django parses it into request.FILES. Files below FILE_UPLOAD_MAX_MEMORY_SIZE (2.5 MB) stay in memory (InMemoryUploadedFile), larger ones go to a temp file (TemporaryUploadedFile). DATA_UPLOAD_MAX_MEMORY_SIZE limits non-file body size; there is no default upper limit for files, so enforce one at the proxy and in validators.
Model side:
def doc_path(instance, filename):
ext = Path(filename).suffix.lower()
return f"docs/{instance.owner_id}/{uuid4().hex}{ext}"
class Document(models.Model):
file = models.FileField(upload_to=doc_path, validators=[validate_size, FileExtensionValidator(["pdf", "png"])])upload_tocan be a callable returning a path relative to storage root: use it to bucket by owner or date and to discard the client's name. Never build paths fromfilenamedirectly:get_valid_name()andFileSystemStoragestrip path separators, but you should still not trust names.- If a name already exists,
Storage.get_available_name()appends a random suffix instead of overwriting. - Validators:
FileExtensionValidatorchecks the extension only; also check size (file.size) and real type (magic bytes viapython-magic, or open images with Pillow'sverify()). Do not trust thecontent_typeheader. - Storage backends: configure
STORAGES = {"default": {"BACKEND": ...}, "staticfiles": {...}}(Django 4.2+). Usedjango-storagesfor S3, GCS or Azure. Tests can useInMemoryStorage(Django 4.2+). - Serving: do not serve
MEDIA_ROOTthrough Django in production. Use signed, expiring URLs from object storage, or X-Accel-Redirect style offloading for permission checks. Serve withContent-Disposition: attachmentand from a separate domain to prevent stored XSS via HTML or SVG uploads. - Cleanup: deleting a model row does not delete the file. Remove it in
post_delete(after commit) or use a periodic job to remove orphans. - Large files: use direct-to-bucket uploads via pre-signed URLs, then store the key.
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
import tempfile
from pathlib import Path
from uuid import uuid4
from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage, InMemoryStorage
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.validators import FileExtensionValidator
from django.db import connection, models
root = Path(tempfile.mkdtemp())
disk = FileSystemStorage(location=str(root))
def validate_size(f):
if f.size > 1024:
raise ValidationError("File larger than 1 KB")
def doc_path(instance, filename):
return f"docs/{instance.owner}/{uuid4().hex}{Path(filename).suffix.lower()}" # client name is discarded
class Document(models.Model):
owner = models.CharField(max_length=20)
file = models.FileField(upload_to=doc_path, storage=disk,
validators=[validate_size, FileExtensionValidator(["pdf", "txt"])])
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Document)
doc = Document(owner="asha", file=SimpleUploadedFile("../../EVIL NAME.TXT", b"hello", content_type="text/plain"))
doc.full_clean()
doc.save()
print("stored under:", doc.file.name.startswith("docs/asha/"), doc.file.name.endswith(".txt"), "evil" not in doc.file.name.lower())
print("size and content:", doc.file.size, doc.file.read())
for name, data in [("script.exe", b"x"), ("big.txt", b"x" * 2000)]:
bad = Document(owner="asha", file=SimpleUploadedFile(name, data))
try:
bad.full_clean()
except ValidationError as exc:
print(name, "->", exc.message_dict["file"])
# Deleting the row does not remove the file
path = Path(doc.file.path)
doc.delete()
print("file still on disk after row delete:", path.exists())
path.unlink()
mem = InMemoryStorage() # handy in tests: nothing touches the disk
saved = mem.save("report.txt", ContentFile(b"abc"))
print("in-memory:", saved, mem.exists(saved), mem.open(saved).read())
second = mem.save("report.txt", ContentFile(b"def"))
print("collision gets a new name:", second != "report.txt", second.startswith("report_"))
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Files are written to a temporary folder. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): stored under: True True True size and content: 5 b'hello' script.exe -> ['File extension “exe” is not allowed. Allowed extensions are: pdf, txt.'] big.txt -> ['File larger than 1 KB'] file still on disk after row delete: True in-memory: report.txt True b'abc' collision gets a new name: True True
Key points
- request.FILES holds UploadedFile objects; large ones spool to disk
- upload_to callable builds your own path and name
- Validate size, extension and real content, not the client's header
- Use STORAGES and django-storages; InMemoryStorage in tests
- Deleting the row does not delete the file
Common mistakes
- Using the client's filename in the storage path
- Validating only the extension or content_type header
- Serving user uploads from the app domain with inline HTML or SVG
- Expecting deleting a row to delete the file
- Forgetting to limit upload size at the proxy and in validators
- Serving MEDIA_ROOT with Django in production
Follow-ups
- How do pre-signed uploads to S3 work with Django?
- How would you scan uploads for malware?
- How do you process images asynchronously after upload?
Tips
- Describe the upload flow
- Show upload_to with a generated name
- Mention cleanup of orphan files