Django ignores DEBUG value when I use os.environ, why?

In my Django settings, I have the following:

DEBUG = os.environ ['DEBUG_VALUE']

Where DEBUG_VALUE = False

However, when I do this, Django keeps showing complete error messages. If I manually add DEBUG = False

it it works and shows 500 errors.

For some reason, Django ignores this when I use the value os.environ

.

I have confirmed which DEBUG_VALUE

is False, but it outputs to a file.

I even tried:

DEBUG = bool (os.environ ['DEBUG_VALUE'])

and still shows complete errors.

+3


source to share


3 answers


The value 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'

      

+4


source


There django-environ

is an easy way to manage this in the package , which is more reliable and elegant, I think, than manually parsing 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 the boolean and provide an optional default:



import environ
env = environ.Env()
MY_DEBUG_ENV_VAR = env.bool('MY_DEBUG_ENV_VAR', default=False)

      

TA-dah! The Env () object also has a variety of other methods (for example, for parsing integers, floats, strings, etc., etc.).

NB I found this though the django-cookiecutter app, which has a bunch of equally useful things pre-installed, is a great starting point for projects, no matter if you're new or experienced with django.

+2


source


Maybe you want something more forgiving. First, allow local definition for development purposes. And only if not defined, get it from an environment variable, but use a 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'.lower()

      

+1


source







All Articles