← Back to Django, page 5

django-0084 · Medium mid

How do file uploads work in Django, and how do you validate, name and store them safely with FileField and storage backends?

Uploaded files arrive in request.FILES as UploadedFile objects (kept in memory when small, spooled to a temporary file when large). A FileField saves them through a storage backend, configured with STORAGES (FileSystemStorage by default, S3 and others through packages). Validate size, extension and real content, generate your own names in upload_to instead of trusting the client filename, serve user files from a separate domain or with forced downloads, and use object storage in production.

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:

python
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_to can 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 from filename directly: get_valid_name() and FileSystemStorage strip 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: FileExtensionValidator checks the extension only; also check size (file.size) and real type (magic bytes via python-magic, or open images with Pillow's verify()). Do not trust the content_type header.
  • Storage backends: configure STORAGES = {"default": {"BACKEND": ...}, "staticfiles": {...}} (Django 4.2+). Use django-storages for S3, GCS or Azure. Tests can use InMemoryStorage (Django 4.2+).
  • Serving: do not serve MEDIA_ROOT through Django in production. Use signed, expiring URLs from object storage, or X-Accel-Redirect style offloading for permission checks. Serve with Content-Disposition: attachment and 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.
python
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