Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, Django - Accessing Environment Variables in settings.py

Tags:

python

django

Within my project, I want to send an email with python/Django. In order to do this, I need to specify multiple settings, and one of them is the password for my email. I want to retreive this from an environment variable.

When I reference the environment variable in settings.py, I get a message implying the value is wrong and not my actual password. I ensured that the environment variable is set to my actual password within bash_profile, and when I hardcoded my password in the settings file, the email is sent successfully.

This implies the issue is occurring when trying to retrieve the password as an environment variable.

SETTINGS.py:

import os
# me trying to retrieve password
EMAIL_HOST_PASSWORD = os.environ.get('email_password')

Anybody know the issue? Thank you.

like image 595
NodeReact020 Avatar asked Aug 04 '26 03:08

NodeReact020


1 Answers

I ensured that the environment variable is set to my actual password within bash_profile

If you are following best practices and running Django in a virtual environment, it has a different set of environment variables. I suspect if you changed your setting to os.environ['email_password'] you would get a KeyError, because that environment variable is not set.

There are a number of ways to export environment variables, but just to prove to yourself that this is the problem, export the value right in the command line with your virtual environment enabled, then run your project and try sending the email.

Edit

Since you're using pipenv, you can simply add a .env file in the root of your project, and pipenv will automatically set those environment variables for you when you activate the virtual environment.

.env

SECRET_KEY=asolidsecretkey
email_password=somesecurepassword
...
like image 123
Greg Kaleka Avatar answered Aug 05 '26 17:08

Greg Kaleka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!