Using TOML for Django Configuration Files

python django tutorial TOML

2023-03-17

Now that TOML is part of the Python standard library as of 3.11, you can easily use it with Django. Previously, I used the django-environ package to manage my Django environment variables. If you’re like me and prefer to keep your requirements.txt file as minimal as possible, then switching to TOML could be the ticket for you as well.

I’m using as a minimally modified version of the setup from this Real Python article.

How To Use TOML

Step 1

In your Django project’s main directory create a folder called config (or whatever your prefer to call it). It should look like this:

.
├── config
├── db.sqlite3
├── manage.py
├── myapp
├── myproject
└── venv

Step 2

Inside of the new config folder, create two files: __init__.py and config.toml.

Step 3

In __init__.py add the following:

import pathlib
import tomllib

path = pathlib.Path(__file__).parent / "config.toml"
with path.open(mode="rb") as fp:
    CFG = tomllib.load(fp)

Step 4

Inside config.toml is where you will add your environment variables. For example:

DEBUG=true
SECRET_KEY='supersecretkey!'

NOTE: TOML booleans are lowercased while Python booleans are uppercased. tomllib will convert these to proper a Python bool

Step 5

Finally, to use the environment variables, import CFG from config. For example in the Django project’s settings.py file:

from config import CFG
...

SECRET_KEY = CFG['SECRET_KEY']
DEBUG = CFG['DEBUG']
...

That’s all you need. Now there will be one less requirement you need to worry about when creating a Django project. (Or any other Python project for that matter.)

Thank you for reading. I hope you find this tutorial helpful! If you have any comments or corrections, please let me know. I can be found on LinkedIn and Mastodon.




Go Back