0

I'm setting up Django using os.getenv to prepare it for deploying using Docker but it seems it is not reading the .env file. Any idea why is not reading it?

Here is the setup:

.env

SECRET_KEY=foo
DEBUG=True
ALLOWED_HOSTS=localhost,127.0.0.1

settings.py abstraction

import os
from pathlib import Path


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = os.getenv('DEBUG')
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS')
sinoroc
  • 18,409
  • 2
  • 39
  • 70
Rodragon
  • 135
  • 3
  • 12
  • 1
    Does this answer your question? [Reading in environment variables from an environment file](https://stackoverflow.com/questions/40216311/reading-in-environment-variables-from-an-environment-file) – Tiki Mar 21 '21 at 22:02
  • Have you written in manage.py how to find your .env file? (usually people forget to do this) – alv2017 Mar 21 '21 at 22:04
  • @alv2017 No, I had no idea you have to edit `manage.py`. Could you provide any example? – Rodragon Mar 21 '21 at 22:14
  • If you cannot install extra packages then you must source the .env (`source .env`) file before running manage.py. – Tiki Mar 22 '21 at 03:17

4 Answers4

1

You can use python-decouple to get the environment variable stored in the root of your project in a .env file.

from decouple import config

SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
EMAIL_HOST = config('EMAIL_HOST', default='localhost')
EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)

Note: for changes to apply you need to restart the server.

Martins
  • 1,130
  • 10
  • 26
0

I'm using python-dotenv in order to implement dotenv functionality. If you want Django to find your .env file, you need to modify manage.py and wsgi.py files.

# manage.py
import os
import sys
import dotenv


def main():
    """Run administrative tasks."""

    # dotenv settings
    dotenv.load_dotenv(
        os.path.join(os.path.dirname(__file__), '.env')
    )
    
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

    if os.getenv('DJANGO_SETTINGS_MODULE'):
        os.environ['DJANGO_SETTINGS_MODULE'] = os.getenv('DJANGO_SETTINGS_MODULE')

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()
# wsgi.py

import os
import dotenv

from django.core.wsgi import get_wsgi_application

# dotenv settings
dotenv.load_dotenv(
    os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')
)

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

if os.getenv('DJANGO_SETTINGS_MODULE'):
 os.environ['DJANGO_SETTINGS_MODULE'] = os.getenv('DJANGO_SETTINGS_MODULE')

application = get_wsgi_application()
alv2017
  • 752
  • 5
  • 14
  • I believe that might do the work but in my case I need it without using dotenv, just python without extra packages – Rodragon Mar 21 '21 at 23:32
  • 1
    The key thing is that in Django you need to tell Django app where .env file is, otherwise it has no clue about it. The job of dotenv package is to a) find .env file; b) read the variables from .env into OS environment variables. Have a look at dotenv packages, there are lots of them, even if you are not willing to use them, you can pick up an idea how they do that. – alv2017 Mar 22 '21 at 00:01
0

When deploying via docker-compose, you can specify in the docker-compose file.bml in the container settings [web]:

web:

...

env_file:

- ./.env

It worked for me without using additional packages. In my case , the file .env is located in the directory where docker-compose.yml is located

akchau
  • 11
  • 1
  • 1
    Please write your answer in English, as Stack Overflow is an [English-only site](//meta.stackoverflow.com/a/297680). – 4b0 Dec 12 '22 at 15:36
  • If you feel more comfortable writing in Russian, please visit our sister site [ru.so]. – Adriaan Dec 12 '22 at 15:38
-1

To get environment variables from docker or from the AWS Elastic Beanstalk i use os.environ.get('SECRET_KEY'), this is generally more reliable than os.environ['SECRET_KEY']

Beikeni
  • 832
  • 7
  • 17