django 2 not able to load env variables from the .env file to setting.py file
Solution 1
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'))
Solution 2
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")
Solution 3
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"))
Solution 4
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"
somesh
Updated on June 26, 2022Comments
-
somesh almost 2 years
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
DEBUG=on SECRET_KEY=ksmdfw3324@#jefm DATABASE_URL=psql://urser:[email protected]:8458/database SQLITE_URL=sqlite:///my-local-sqlite.db CACHE_URL=memcache://127.0.0.1:11211,127.0.0.1:11212,127.0.0.1:11213 REDIS_URL=rediscache://127.0.0.1:6379/1? client_class=django_redis.client.DefaultClient&password=ungithubbed-secret MYSQL_DATABASE = student MYSQL_USERNAME = root SECRET_KEY=secret-key
this is my setting.py file
import os from os.path import join, dirname from dotenv import load_dotenv dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) # Accessing variables. dbname = os.getenv('MYSQL_DATABASE') secret_key = os.getenv('SECRET_KEY') # Using variables. print(dabname) print(secret_key)
i installed
pip install -U python-dotenv
Issue is i am not able to get environment variable inside settings file
while trying
python manage.py runserver
i am getting this errorC:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\dotenv\main.py:65: UserWarning: File doesn't exist warnings.warn("File doesn't exist {}".format(self.dotenv_path)) Traceback (most recent call last): File "manage.py", line 28, in <module> execute_from_command_line(sys.argv) File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\mehul\AppData\Local\Programs\Python\Python36- 32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\xampp\htdocs\epitastudent\epitastudent\settings.py", line 25, in <module> load_dotenv() File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\dotenv\main.py", line 255, in load_dotenv return DotEnv(f, verbose=verbose).set_as_environment_variables(override=override) File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\site- packages\dotenv\main.py", line 98, in set_as_environment_variables os.environ[k] = v File "C:\Users\mehul\AppData\Local\Programs\Python\Python36-32\lib\os.py", line 675, in __setitem__ self.putenv(key, value) ValueError: embedded null character
I am not sure how to create development and production environment variable and about this embedded null character. pls help me any one Thanks in advance
Edit: I got now .env file to inside settings
import os import environ root = environ.Path(__file__) - 3 # three folder back (/a/b/c/ - 3 = /) env = environ.Env(DEBUG=(bool, False),) # set default values and casting environ.Env.read_env() # reading .env file print(os.getenv('DATABASE_NAME'))
How can i differentiate development env credentials and production credentials
-
Islam Murtazaev about 5 yearsYou can create .env.production, .env.dev and .env.local, then use docker containers for different environments.
-
-
somesh over 5 years@lvan thanks for reply not working i tried this also. It is giving ValueError: embedded null character
-
Brendan Metcalfe over 4 yearshow do you then assign it to do something like env.bool('DEBUG', default=False) ??
-
Alex Burkov over 4 yearsif I understand you correctly, I used something like that
env = environ.Env(DEBUG=(bool, False))