Django: How to implement Python Decouple

Adding Python Decouple to our Django web application.

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 file. Upon realizing this, you will think, how can I keep everything separate and safe.

Enter - python-decouple.

So, let's get started...

Step 1:

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

pip install python-decouple

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 as-is into your .env file.


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:


from decouple import config

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 and modify your existing debug and secret key values with the following:


DEBUG = config('DEBUG', cast=bool)SECRET_KEY = config('SECRET_KEY')