{"record":{"id":"fc7bc26fdb443c77","repo":"django/django","slug":"file-name-s-includes-path-elements","errorCode":null,"errorMessage":"File name '%s' includes path elements","messagePattern":"File name '(.+?)' includes path elements","errorType":"validation","errorClass":"SuspiciousFileOperation","httpStatus":400,"severity":"warning","filePath":"django/core/files/utils.py","lineNumber":21,"sourceCode":"\nfrom django.core.exceptions import SuspiciousFileOperation\n\n\ndef validate_file_name(name, allow_relative_path=False):\n    # Remove potentially dangerous names\n    if os.path.basename(name) in {\"\", \".\", \"..\"}:\n        raise SuspiciousFileOperation(\"Could not derive file name from '%s'\" % name)\n\n    if allow_relative_path:\n        # Ensure that name can be treated as a pure posix path, i.e. Unix\n        # style (with forward slashes).\n        path = pathlib.PurePosixPath(str(name).replace(\"\\\\\", \"/\"))\n        if path.is_absolute() or \"..\" in path.parts:\n            raise SuspiciousFileOperation(\n                \"Detected path traversal attempt in '%s'\" % name\n            )\n    elif name != os.path.basename(name):\n        raise SuspiciousFileOperation(\"File name '%s' includes path elements\" % name)\n\n    return name\n\n\nclass FileProxyMixin:\n    \"\"\"\n    A mixin class used to forward file methods to an underlying file\n    object. The internal file object has to be called \"file\"::\n\n        class FileProxy(FileProxyMixin):\n            def __init__(self, file):\n                self.file = file\n    \"\"\"\n\n    encoding = property(lambda self: self.file.encoding)\n    fileno = property(lambda self: self.file.fileno)\n    flush = property(lambda self: self.file.flush)\n    isatty = property(lambda self: self.file.isatty)","sourceCodeStart":3,"sourceCodeEnd":39,"githubUrl":"https://github.com/django/django/blob/ae25a40be07e8a749edf526df37c93e59d4a22c9/django/core/files/utils.py#L3-L39","documentation":"Raised as a django.core.exceptions.SuspiciousFileOperation by validate_file_name() (the default code path, allow_relative_path=False) when the given name is not equal to its own basename — i.e. it contains '/', '\\', or other path separators. Django requires file names to be bare names so the storage backend can place them safely; any embedded path is rejected.","triggerScenarios":"Calling storage.save('subdir/file.txt', content) or FieldFile.save with a name containing a slash; passing a full Windows path like 'C:\\\\tmp\\\\f.txt'; assigning a model FileField a value containing directory separators.","commonSituations":"Saving uploads preserving the original browser sub-path; generating names with os.path.join('user_1', 'doc.pdf') instead of a flat name; copying paths from an external source into storage.save.","solutions":["Flatten the name to its basename: name = os.path.basename(name) before calling save().","If you need subdirectories, use a storage backend/path that supports it and pass allow_relative_path=True only after sanitizing (see error 400).","Construct flat, unique names yourself, e.g. name = f'{uuid4().hex}.pdf'."],"exampleFix":"// before\nstorage.save(os.path.join('uploads', upload.name), content)\n// after\nstorage.save(os.path.basename(upload.name), content)","handlingStrategy":"validation","validationCode":"import os\ndef flat_name(name):\n    base = os.path.basename(str(name).replace('\\\\', '/'))\n    if base in ('', '.', '..'):\n        raise ValueError(f'cannot derive a flat name from {name!r}')\n    return base","typeGuard":"import os\ndef is_flat_filename(name: str) -> bool:\n    return name == os.path.basename(str(name).replace('\\\\', '/'))\n","tryCatchPattern":"from django.core.exceptions import SuspiciousFileOperation\ntry:\n    storage.save(name, content)\nexcept SuspiciousFileOperation:\n    storage.save(os.path.basename(name), content)","preventionTips":["Never embed directories in names passed to storage.save / FileField.","Use os.path.basename() defensively at the boundary where untrusted names enter.","Generate flat unique names yourself instead of preserving client subpaths."],"tags":["security","file-storage","validation","django"],"analyzedSha":"ae25a40be07e8a749edf526df37c93e59d4a22c9","analyzedAt":"2026-08-06T21:46:51.801Z","schemaVersion":2},"datasetVersion":"2026-08-07T02:17:10.218Z"}