django 2 not able to load env variables from the .env file to setting.py file

前端 未结 5 1972
太阳男子
太阳男子 2021-01-14 13:08

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

相关标签:
5条回答
  • 2021-01-14 13:54

    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"
    
    0 讨论(0)
  • 2021-01-14 13:56

    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'))
    
    0 讨论(0)
  • 2021-01-14 13:57

    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")
    
    0 讨论(0)
  • 2021-01-14 13:59

    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)

    0 讨论(0)
  • 2021-01-14 14:01

    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"))
    
    0 讨论(0)
提交回复
热议问题