Richard
Richard

Reputation: 65510

Django can't see environment variables?

I'm trying to run Django (1.10) but getting an error:

(.venv)$ ./manage.py runserver 0.0.0.0:8000
Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  ...
  File "/home/myapp/myapp/myapp/myapp/settings/local.py", line 5, in <module>
    from .base import *
  File "/home/myapp/myapp/myapp/myapp/settings/base.py", line 64, in <module>
    'NAME': utils.get_env_setting('RETR_DB_NAME'),
  File "/home/myapp/myapp/myapp/common/utils.py", line 13, in get_env_setting
    raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the RETR_DB_NAME env variable

But the environment variable is set:

(.venv) $ echo $RETR_DB_NAME
myname

The code in question looks like this:

def get_env_setting(setting):
  """ Get the environment setting or return exception """
  try:
    return environ[setting]
  except KeyError:
    error_msg = "Set the %s env variable" % setting
    raise ImproperlyConfigured(error_msg)
 ...
'NAME': utils.get_env_setting('RETR_DB_NAME'),

How come I can see the environment variable, but Django can't?

Upvotes: 1

Views: 2196

Answers (3)

Milad shiri
Milad shiri

Reputation: 990

If you're using shells like zsh, make sure to put export key=value in the config, e.g. ~/.zshrc.

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155323

Odds are you forgot to export it. You can check if that's the problem with:

export -p | fgrep RETR_DB_NAME

which will output nothing if you forgot to export, and export can be used to make it exported (whether or not it was already exported, it's not an error to export twice) with:

export RETR_DB_NAME

Upvotes: 5

Gautam
Gautam

Reputation: 7958

Personally I recommend getting the variable using os.getenv which allows you to return a default value.

Anyway make sure the environment variable is set using export RETR_DB_NAME='db_name' instead of RETR_DB_NAME='db_name'

Upvotes: 1

Related Questions