Django security best practices

Recently updated at


Django is a powerful web development framework. It sells itself as the web framework for perfectionists with deadlines. And this makes sense, considering it is a framework with batteries included.

The project learned a lot of the past from content management systems (CMS) and frameworks in general. When it comes to security, Django is there to prevent common mistakes. Still, one should know the measures in place and properly configure them. Within this checklist, we have a look at the options.


Setting up the right disk structure

Every project begins with a structure on the disk. By using django-admin with the startapp or startproject command, the related directory structure is created. The first mistake is around the corner. When serving the project via a web server, any code is in the 'root' directory of the web server, might be disclosed.

When you set your virtual host configuration to /home/www-user/myproject/project, make sure that any of the code is at least level higher. This way the web server can't reach it directly (in /home/www-user/myproject).


Keeping secrets

A secret should remain secret. Within Django, there is one big secret key that needs to be properly protected. The variable is found in and goes by the name SECRET_KEY. Preferably it needs to be unique. And as the name implies, it should always be kept secret.

One of the biggest risks is that a secret key is checked into source code repositories by accident. To prevent this, generate a random secret key and overrule it in a separate configuration file. This way it is fine to have in the repository, while the secrets are stored somewhere else.

import uuid
SECRET_KEY = uuid.uuid4()