Search code examples
djangodotenvpython-dotenv

How do I use .env in Django?


My goal is to email using Python Django without having my email password being shown in the actual code. After some research, I guess I can store my password in an .env file and then access the password from the .env file. So, I currently have an .env file in my Django project with this line of code:

export EMAIL_HOST = 'smtp.gmail.com'

And in my settings.py, I have these:

import environ
env = environ.Env()
environ.Env.read_env()
EMAIL_HOST = os.environ.get('EMAIL_HOST')
print(EMAIL_HOST)

But the printed result is None. print(os.environ) spits out something though. How can I get my .env file to work?


Solution

  • Not only in Django, in general use the library python-dotenv.

    from dotenv import load_dotenv
    import os
    
    load_dotenv()
    EMAIL_HOST = os.getenv("EMAIL_HOST")