docs: https://django-environ.readthedocs.io/en/latest/
install:
pip install django-environ
NOTE: No need to add it to INSTALLED_APPS.
Then create a .env
file to project path:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
DEBUG=on SECRET_KEY=your-secret-key DATABASE_URL=psql://urser:un-githubbedpassword@127.0.0.1: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
then settings.py:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import environ # initialize env env = environ.Env( # set casting, default value DEBUG=(bool, False) ) # reading .env file environ.Env.read_env() # False if not in os.environ DEBUG = env('DEBUG') # Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ SECRET_KEY = env('SECRET_KEY') # Parse database connection url strings like psql://user:pass@127.0.0.1:8458/db DATABASES = { # read os.environ['DATABASE_URL'] and raises ImproperlyConfigured exception if not found 'default': env.db(), # read os.environ['SQLITE_URL'] 'extra': env.db('SQLITE_URL', default='sqlite:////tmp/my-tmp-sqlite.db') } CACHES = { # read os.environ['CACHE_URL'] and raises ImproperlyConfigured exception if not found 'default': env.cache(), # read os.environ['REDIS_URL'] 'redis': env.cache('REDIS_URL') }