Django File Upload With Size Limit
Handle file uploads in Django with size limit type validation and virus scan scheduling.
Code
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_SIZEshort-circuits the flow with an earlyraisewhen 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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.