tait.tech

Django: SuspiciousFileOperation: Detected path traversal attempt


When trying to add a locally stored file to a Django model recently, I had this issue. Believe it or not, this is a good thing!

Django is build to take the security aspects of a system and sort of hide them behind a few onion layers of API calls and security middleware. This is good for your average developer. It stops them from making stupid mistakes like not using CSRF in secure forms, the allowing of insecure passwords, dangerous passing of user values into a document, et cetera. That said, sometimes when you are doing something, and even if it seems relatively safe, Django will flag something you do as suspicious, halting development and wasting time.

So that said, here’s why the issue happened, why this is a good thing, and how to get around it.

Why Django is a lifesaver!

Django, in an effort to help keep your application secure, does not want to access files with an absolute path. This is to stop what is known as a directory traversal attack. So when you try to access something by using your environment variables, i.e. os.environ["PWD"], you may find that Django will give you errors if you try to pass this path into one of their Django, in an effort to help keep your application secure, does not want to access files with an absolute path.

# django's files are just wrappers around python's
from django.core.files import File

df = File(open(os.environ["PWD"] + "path1/file.pdf"))

This will give you a nasty error: