How to setup environment variables for Django projects

Hello, welcome to the devmaesters website. In this post I am going to be guiding you through the process of setting up environment variables for your Django project.

First thing you need to do is to install the python-dotenv package by executing the command below in your terminal;

pip install python-dotenv

After successfull installation of the package, go to the root directory of your Django project and create a .env file. 

Next go to your project's settings.py file and import os and dotnev as shown below;

import os
import dotenv

Add the configuration below after your import codes in settings.py 

dotenv_file = os.path.join(BASE_DIR, ".env")
if os.path.isfile(dotenv_file):
    dotenv.load_dotenv(dotenv_file)

This sets up the .env file we created previously to be the source of our environment variables.

And that's all for setting it up. Below is an example on how to use it;

Lets say we want to hide our Django secret key by using environment variables, all we need to do is to create an environment variable called SECRET_KEY in our .env file and set its value to our actual secret key as shown below

SECRET_KEY = django-MASeyyd-=k@mr1@hfhfj6)0p(hhff(mp(mkr@5)^njpp&+at*qdd*b&=@

then in settings.py we replace our SECRET_KEY configuration with the configuration shown below;

SECRET_KEY = os.environ['SECRET_KEY']

And lastly create a .gitignore file in the root of your project and add the .env file you just created to it.

# Environments
.env

 

Conclusion

Through this post I have been able to guide you through the process of setting up environment variables for your Django project. If you have any questions feel free to drop a comment down below and I'll reply you as soon as I can.

Author
author-image

Hello, my name is Abubakar Zakari. Am a budding fullstack developer from Nigeria who loves developing softwares and learning new frameworks and langauges.

Comment

Select image


Comments
No comment yet

DEVMAESTERS

Newsletter

Services

Frontend Development |Backend Development |Full Website Development |Bootstrap Website upgrades | Website Debbugging | Website Hosting & deployment

Contact

Interested in hiring me or collaborating with me on a project, click on any of the links below to get my social media handle

Or contact me via Tel: (+234)-806-225-7480 | Email: abubakarzakari1703@gmail.com

Copywright@devmaesters.com
Privacy Policy

By using our website,
you agree that devmaesters can store cookies on your device and disclose information in accordance with our privacy policy.