Django ignoring DEBUG value when I use os.environ, why?
The django-environ
package has a simple way of managing this that is more robust and elegant, I think, than having to manually parse the string value (which will always evaluate to true) - you can import your environment as an object.
Export the environment variable and install the package:
export MY_DEBUG_ENV_VAR=False
pip install django-environ
Then in django, import the environment as an Env() object and use the bool() method to parse a boolean and provide an optional default value:
import environ
env = environ.Env()
MY_DEBUG_ENV_VAR = env.bool('MY_DEBUG_ENV_VAR', default=False)
Tada! The Env() object also has a bunch of other methods (e.g. for parsing integers, floats, strings etc etc).
NB I found this though the django-cookiecutter application, which has a bunch of equally useful things preinstalled and is a great starting point for projects whether you're new or experienced with django.
Maybe you want something more forgiving. First allow the local definition for development purposes. And only if not defined, get it from environment variable, but use the case insensitive comparison (since the person doing the deployment might not be the developer writing this line of code).
try:
DEBUG = DEBUG_VALUE_LOCAL
except NameError:
DEBUG = os.environ.get('DEBUG_VALUE').lower() == 'true'
Alternatively, you can evaluate with int(String), if you use 1/0 values, instead of True/False for the environment variable:
# Set DEBUG flag. Default is 0 (considered as False in conditions)
DEBUG = int(os.environ.get('DEBUG_VALUE', 0))
The value of os.environ['DEBUG_VALUE']
is a string and bool('non empty string') == True
.
You should do something similar to:
DEBUG = os.environ['DEBUG_VALUE'] == 'TRUE'