JSRB
JSRB

Reputation: 2623

Why does Environ not set the variable in a Django project root other than the main?

So I have a .env file in my Django project root containing several variables.

When I use them within the same project root (e.g. in settings.py) it works, but once I try to access a variable within another root/module it fails:

# other root than .env
import environ

# Initialise environment variables
env = environ.Env()
environ.Env.read_env()

# Get the iCloud application password via env
mail_password = env('MAIL_PW')

# --> returns django.core.exceptions.ImproperlyConfigured: Set the MAIL_PW environment variable

This however works:

# same root as .env
import os
import environ

# Initialise environment variables
env = environ.Env()
environ.Env.read_env()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY')

Upvotes: 1

Views: 1829

Answers (1)

Yevhen Bondar
Yevhen Bondar

Reputation: 4707

Your first code fails, because environ.Env.read_env cannot find the .env file.

Here the source

    @classmethod
    def read_env(cls, env_file=None, overwrite=False, **overrides):
        """Read a .env file into os.environ.

        If not given a path to a dotenv path, does filthy magic stack
        backtracking to find the dotenv in the same directory as the file that
        called read_env.
        ...

Directory with your module has no .env file and read_env cannot import it.

You can just import all your .env variables in settings.py as suggested in documentation. Then you can import settings in other modules

settings.py

import os
import environ

# Initialise environment variables
env = environ.Env()
environ.Env.read_env()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY')

module.py

from settings import SECRET_KEY

print(SECRET_KEY)
...

Upvotes: 2

Related Questions