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
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.