DEV Community

Cover image for Django: How to implement Python Decouple
Arno Pretorius
Arno Pretorius

Posted on

Django: How to implement Python Decouple

Why do we need Python Decouple?

As we continue to build our Django web application, we will eventually come to a realization that there is a lot of sensitive information that is stored in our settings.py file. Upon realizing this, you will think, how can I keep everything separate and safe.

Enter - python-decouple.


Step 1:
To install python-decouple in your application, open up your terminal and type in the following command:

pip install python-decouple
Enter fullscreen mode Exit fullscreen mode

Step 2:
Create a .env file in your repository’s root directory.


Step 3:
As a test, we will store some important data, such as debug and our secret key. So, simply copy + paste your debug and secret key from settings.py as-is into your .env file.

DEBUG=False
SECRET_KEY='my_secret_key'
Enter fullscreen mode Exit fullscreen mode

Step 4:
If you happen to be using Git be sure to .gitignore your .env file for security purposes.

Step 5:
Next, you need to import the decouple library:

# settings.py

from decouple import config
Enter fullscreen mode Exit fullscreen mode

Step 6:
Now we want to get our parameters.
Decouple will always return our data as a string. To solve this problem, we need to cast it to a bool if we are expecting a Boolean or to an int if we are expecting an integer. Go back to your settings.py and modify your existing debug and secret key values with the following:

# settings.py

DEBUG = config('DEBUG', cast=bool)SECRET_KEY = config('SECRET_KEY')
Enter fullscreen mode Exit fullscreen mode

A final note…
For those that are interested in learning Django from scratch, feel free to check out my latest course:

Python Django: Ultimate Beginners Course - 2022

Top comments (0)