[Fixed]-How do I use .env in Django?

54👍

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

7👍

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

👤josue

0👍

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.

Leave a comment