Forums

What is the correct way to use environment variable for db pass word django settings?

Hi,

In django, using a .env file, with an entry like this:

db_pass = 'my db pass word'

I have gotten the environment variable to work for Secret Key.

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'DIRT_SECRET_KEY'

with a matching entry in the .env file that looks like this:

DIRT_SECRET_KEY = 'some really long alpha numeric special character combination'

But for some reason it is not working for the database password.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mwshovel$dirt',
    'USER': 'mwshovel',
    'PASSWORD': WHAT GOES HERE?, <--- is it in quotes, brackets, 
    'HOST': 'mwshovel.mysql.pythonanywhere-services.com',
    }
}

Hi there, check out our help pages on this topic.

I did. That was how I set it up in the first place. Maybe the question isn''t clear. Given a line in the .env file like ths:

db_pass='my_db_pass_word'

How do I format the string 'db_pass' in the settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mwshovel$dirt',
    'USER': 'mwshovel',
    'PASSWORD': 'db_pass' or db_pass or "db_pass" or .....?,
    'HOST': 'mwshovel.mysql.pythonanywhere-services.com',
#   'PORT': '3306'
    }
}

When I know that this works entry in .env file:

DIRT_SECRET_KEY = 'some really long alpha numeric special character combination'

Matching line in settings file:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'DIRT_SECRET_KEY'

When I put the variable name in the same way I did for SECRET_KEY, single quotes around the variable name it throws an error.

I think you need to get it from the os.environ dictionary instead of passing a simple string?

you mean something like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mwshovel$dirt',
    'USER': 'mwshovel',
    'PASSWORD': os.eviron('db_pass') or os.environ['db_pass'] #<--------------------.?,
    'HOST': 'mwshovel.mysql.pythonanywhere-services.com',
#   'PORT': '3306'
    }
}

yes. you should lookup the os.environ documentation

In case it's helpful to someone else. One way you can solve for this is to set up your .env with:

DATABASE_ENGINE='your_database_engine_goes_here'
DATABASE_NAME='your_database_name_goes_here'
DATABASE_USER='your_database_user_name_goes_here'
DATABASE_PWD='your_database_password_goes_here'
DATABASE_HOST='your_database_host_string_here'

Then, in your settings file you can:

DATABASES = {
    'default': {
        'ENGINE': os.getenv('DATABASE_ENGINE'),
        'NAME': os.getenv('DATABASE_NAME'),
        'USER': os.getenv('DATABASE_USER'),
        'PASSWORD': os.getenv('DATABASE_PWD'),
        'HOST': os.getenv('DATABASE_HOST'),
    }
}

Good luck!