How do I use .env in Django?

42.6k Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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")
0
On

https://gist.github.com/josuedjh3/38c521c9091b5c268f2a4d5f3166c497 created a file utils.py in your project.

1: Create an .env file to save your environment variables.

file env.

DJANGO_SECRET_KEY=%jjnu7=54g6s%qjfnhbpw0zeoei=$!her*y(p%!&84rs$4l85io
DJANGO_DATABASE_HOST=database
DJANGO_DATABASE_NAME=master
DJANGO_DATABASE_USER=postgres

2: For security purposes, use permissions 600 sudo chmod 600 .env

3: you can now use the varibles settigns.py

from .utils import load_env 

get_env = os.environ.get

BASE_DIR = Path(__file__).parent.parent.parent 

load_env(BASE_DIR / "../.env") #here you indicate where your .env file is

SECRET_KEY = get_env("DJANGO_SECRET_KEY", "secret")

This way it can handle multiple environments production or stagins

1
On

You can do it by importing os and creating a .env file where you will specify all the database details for connection.

settings.py file:

    import os
    DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.environ.get('DB_NAME'),
        "USER": os.environ.get('DB_USER'),
        "PASSWORD": os.environ.get('DB_USER_PASSWORD'),
        "HOST": os.environ.get('DB_HOST'),
        "PORT": os.environ.get('DB_PORT'),
    }
}

.env file:

export DB_NAME = dbname
export DB_USER = root
export DB_USER_PASSWORD = root
export DB_HOST = localhost
export DB_DB_PORT = 5432

This example is for PostgreSQL but other DB setup will be exact similar but engine name will need to be changed.