I tried to load environment variables from a file named .env to settings.py file here i created the .env file and settings file same folder.
this is my .env file
I think there are mainly two packages to use
pip install django-environ
and
pip install python-dotenv
I choose to use dotenv, as django-environ give me some error.
Error: The SECRET_KEY setting must not be empty
Below is my working solution, notice that it is square bracket []
when calling os.environ.
My version is Django==2.2.6, python==3.7.5
settings.py
import os
from dotenv import load_dotenv
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
load_dotenv(os.path.join(BASE_DIR, '.env'))
SECRET_KEY = os.environ['SECRET_KEY']
and the .env file is storing in the current directory with
.env
export SECRET_KEY="xxxxxx"
export DB_NAME = "xxx"
Try this instead:
import os
import environ
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
environ.Env.read_env(env_file=os.path.join(BASE_DIR, '.env'))
For future Googlers here's another approach. Inside manage.py
add:
from dotenv import load_dotenv
load_dotenv()
Now you can do the following anywhere else in your project (including settings.py
) to get access to environment variables:
import os
os.environ.get("NAME")
I'm not quite sure, but maybe it has to do with the path to the .env file. Maybe you should try in settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file)))
dotenv_path = os.path.join(BASE_DIR, file.env)
I was unable to load environment variables using load_dotenv() in Python version 3.5 - later versions were working fine.
The workaround is explicitly include the folder containing .env in the path. So, assuming folder project contains .env, settings.py will have following lines:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from dotenv import load_dotenv
load_dotenv(os.path.join(BASE_DIR, "project", ".env"))