Django File Upload With Size Limit

Handle file uploads in Django with size limit type validation and virus scan scheduling.

PythonFile Upload

Code

pythonsnippet
15 lines
from django.core.exceptions import ValidationError
from django.conf import settings
import os

MAX_UPLOAD_SIZE = 10 * 1024 * 1024
ALLOWED_TYPES = {'image/png', 'image/jpeg', 'application/pdf'}

def validate_upload(file):
    if file.size > MAX_UPLOAD_SIZE:
        raise ValidationError(f'File too large: {file.size} > {MAX_UPLOAD_SIZE}')
    if file.content_type not in ALLOWED_TYPES:
        raise ValidationError(f'Unsupported type: {file.content_type}')
    ext = os.path.splitext(file.name)[1].lower()
    if ext not in {'.png', '.jpg', '.pdf'}:
        raise ValidationError(f'Invalid extension: {ext}')

Inside the snippet

Count the function validate_upload as the entire surface area of Django File Upload With Size Limit.

The import line is the dependency contract: ValidationError, settings come from django and nothing else. When the guard condition holds, ValidationError is thrown rather than a bogus value returned.

Caveats

  • External dependency: django — install it before running the snippet.
  • The guard file.size > MAX_UPLOAD_SIZE short-circuits the flow with an early raise when its condition holds.

Using it

The main signature reads def validate_upload(file)

Callers only need validate_upload — everything else stays internal.

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
It throws `ValidationError` before any real work runs, via the guard `file.size > MAX_UPLOAD_SIZE` — handle it at the call site or let it propagate deliberately.
Are there third-party dependencies?
`django` — install it with the package manager before running.