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

前端 未结 5 1983
太阳男子
太阳男子 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"
    

提交回复
热议问题