PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 21, 2022

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

 August 21, 2022     django, environment-variables, python     No comments   

Issue

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

Solution

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


Answered By - Yevhen Bondar
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing