{"record":{"id":"198dea1f95dc8043","repo":"affaan-m/ECC","slug":"file-too-large-max-size-is-5mb","errorCode":null,"errorMessage":"File too large. Max size is 5MB.","messagePattern":"File too large\\. Max size is 5MB\\.","errorType":"validation","errorClass":"ValidationError","httpStatus":null,"severity":"warning","filePath":"skills/django-security/SKILL.md","lineNumber":424,"sourceCode":"    'application/pdf': {'.pdf'},\n}\n\ndef validate_file_type(value):\n    \"\"\"Validate file type using magic bytes and cross-check extension.\"\"\"\n    mime = magic.from_buffer(value.read(2048), mime=True)\n    value.seek(0)\n\n    if mime not in ALLOWED_MIMES:\n        raise ValidationError('Unsupported file type.')\n\n    ext = os.path.splitext(value.name)[1].lower()\n    if ext not in MIME_TO_EXTENSIONS.get(mime, set()):\n        raise ValidationError('File extension does not match file content.')\n\ndef validate_file_size(value):\n    \"\"\"Validate file size (max 5MB).\"\"\"\n    if value.size > 5 * 1024 * 1024:\n        raise ValidationError('File too large. Max size is 5MB.')\n\n# models.py\nclass Document(models.Model):\n    file = models.FileField(\n        upload_to='documents/',\n        validators=[validate_file_type, validate_file_size]\n    )\n\n```\n\nFor environments where installing libmagic is difficult (e.g., minimal containers),\nuse the pure-Python `filetype` package as an alternative:\n\n```python\nimport os\nfrom django.core.exceptions import ValidationError\n\nimport filetype  # pip install filetype","sourceCodeStart":406,"sourceCodeEnd":442,"githubUrl":"https://github.com/affaan-m/ECC/blob/01e15490f04e29cfefe3896951f43db46994d8ee/skills/django-security/SKILL.md#L406-L442","documentation":"Raised by a Django file-upload validator (`validate_file_size`) attached to a `FileField` via the `validators=[...]` kwarg. It triggers when `value.size` (bytes on the `UploadedFile`) exceeds `5 * 1024 * 1024`. Django surfaces it as a form/model `ValidationError`, which the form layer renders next to the field or the DRF layer maps to HTTP 400.","triggerScenarios":"A user uploads a file >5MB to a `Document.file` `FileField` that lists `validate_file_size` in its `validators`. Also fires if the validator is called manually via `field.run_validators(value)` or `full_clean()`.","commonSituations":"Nginx/Apache `client_max_body_size` is larger than 5MB so the request reaches Django only to be rejected by the validator; or the limit was bumped in nginx but not in the Django validator (drift). Also happens when chunks/multipart uploads reassemble over the limit.","solutions":["Confirm the intended cap and make nginx/Apache `client_max_body_size` match (or be slightly smaller than) the Django validator so oversized uploads are rejected at the edge.","If the 5MB cap is wrong, change the constant in `validate_file_size` (and any UI hint) — keep both in sync.","For larger uploads, switch to a chunked/presigned-upload flow (S3 direct, django-storages) instead of raising the validator cap.","Handle the `ValidationError` in the form/view so the user gets a clear message rather than a 500."],"exampleFix":"# before\nif value.size > 5 * 1024 * 1024:\n    raise ValidationError('File too large. Max size is 5MB.')\n\n# after — named constant shared with nginx config and UI hint\nMAX_UPLOAD_BYTES = 5 * 1024 * 1024\nif value.size > MAX_UPLOAD_BYTES:\n    raise ValidationError(f'File too large. Max size is {MAX_UPLOAD_BYTES // (1024*1024)}MB.')","handlingStrategy":"validation","validationCode":"# before binding the validator, reject at the edge\nfrom django.core.exceptions import ValidationError\nMAX_UPLOAD_BYTES = 5 * 1024 * 1024\n\ndef assert_under_limit(upload):\n    if upload.size > MAX_UPLOAD_BYTES:\n        raise ValidationError(f\"File too large: {upload.size} > {MAX_UPLOAD_BYTES}\")\n    return True","typeGuard":"null","tryCatchPattern":"from django.core.exceptions import ValidationError\ntry:\n    doc.full_clean()  # runs validators=[validate_file_size, validate_file_type]\nexcept ValidationError as e:\n    # e.message_dict maps field -> [messages]\n    return render_error(form, e.message_dict)","preventionTips":["Set nginx `client_max_body_size` slightly below the Django cap so oversized uploads never reach Python.","Show the size limit in the upload UI next to the file picker.","Use one shared `MAX_UPLOAD_BYTES` constant across nginx, the validator, and the front-end."],"tags":["django","file-upload","validation","web"],"backgroundTag":null,"analyzedSha":"01e15490f04e29cfefe3896951f43db46994d8ee","analyzedAt":"2026-08-13T00:31:08.655Z","schemaVersion":2},"datasetVersion":"2026-08-13T04:17:16.726Z"}