dev.Im
dev.Im

Reputation: 33

.env keyError in django project

I'm having a hard time because my django project.
Who can help?
I'd like to thank you for your help.

set .env in proeject Root path

SECRET_KEY=exampleKey
DEBUG=False


DB_ENGINE=django.db.backends.mysql
DB_NAME=example
DB_USER=admin

...Blah Blah

project settings.py

import os
import environ

env = environ.Env(DEBUG=(bool, False), )
environ.Env.read_env()

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = env('SECRET_KEY')

DEBUG = env('DEBUG')

...Blah Blah

And when run the project I get an this error message.

Django_workspace/asone/asone/.env doesn't exist - if you're not configuring your environment separately, create one.
  "environment separately, create one." % env_file)

    raise KeyError(key) from None
KeyError: 'SECRET_KEY'

During handling of the above exception, another exception occurred:

/Django_workspace/asone/venv/lib/python3.7/site-packages/environ/environ.py", line 277, in get_value
    raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable

I have a hard time because I'm a django beginner.
Who can help? I'd like to thank you for your help.


.P.S

Thank you so much for your answer. I'm sorry. I'm telling you, there's something I missed out on.

I set up a django-environ package to use the .env in the project.

pip install django-environ

Is there something I'm missing?
What more information will be needed to solve this problem?


.P.S

set up python-dotenv package

pip install python-dotenv.

Change settings.py

import os
from dotenv import load_dotenv

load_dotenv()

...

SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG=os.getenv('DEBUG')

DATABASES = {
    'default': {
        # 'ENGINE': env('DB_ENGINE'),
        # 'NAME': env('DB_NAME'),
        # 'USER': env('DB_USER'),
        # 'PASSWORD': env('DB_PASSWORD'),
        # 'HOST': env('DB_HOST'),
        # 'PORT': env('DB_PORT'),
        'ENGINE': os.getenv('DB_ENGINE'), 
        'NAME': os.getenv('DB_NAME'),
        'USER': os.getenv('DB_USER'),
        'PASSWORD': os.getenv('DB_PASSWORD'),
        'HOST': os.getenv('DB_HOST'),
        'PORT': os.getenv('DB_PORT'),
    }
}
...

and then I met this error message.

Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 562, in configure
    handler = self.configure_handler(handlers[name])
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 735, in configure_handler
    result = factory(**kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py", line 148, in __init__
    BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py", line 55, in __init__
    logging.FileHandler.__init__(self, filename, mode, encoding, delay)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py", line 1087, in __init__
    StreamHandler.__init__(self, self._open())
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py", line 1116, in _open
    return open(self.baseFilename, self.mode, encoding=self.encoding)
FileNotFoundError: [Errno 2] No such file or directory: '/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/logs/logfile'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run
    autoreload.raise_last_exception()
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception
    raise _exception[1]
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute
    autoreload.check_errors(django.setup)()
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/utils/log.py", line 75, in configure_logging
    logging_config_func(logging_settings)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 799, in dictConfig
    dictConfigClass(config).configure()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 570, in configure
    '%r' % name) from e
ValueError: Unable to configure handler 'file'

Is there something I'm missing?

Upvotes: 2

Views: 3252

Answers (2)

harryghgim
harryghgim

Reputation: 1570

There is no environ module in stdlib(standard library of python). So I checked if there is third party module called 'environ' by running pip install environ, which installed it, but when I checked at pypi website, I can't see any valid explanation. I think it's not maintained well.

So I concluded that your environ configuration went a bit odd.

Here's my suggestion

  1. Install python-dotenv module by running pip install python-dotenv. There are many .env module, but this is one of the most popular, well maintained one in my opinion.

  2. Ensure your .env file is in the directory where settings.py is. setting.py will load .env file in the same directory unless specified otherwise

  3. Change your code from this

import os
import environ

env = environ.Env(DEBUG=(bool, False), )
environ.Env.read_env()

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = env('SECRET_KEY')

DEBUG = env('DEBUG')

to this

import os
from dotenv import load_dotenv

load_dotenv()

...

SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG=os.getenv('DEBUG')

...

Change your db setting similar way

DATABASES = {
    'default': {
        'ENGINE': os.getenv('DB_ENGINE'), 
        'NAME': os.getenv('DB_NAME'),
        'USER': os.getenv('DB_USER'),
        # and so on ...
        }
    }
}

Upvotes: 6

Lewis Menelaws
Lewis Menelaws

Reputation: 1186

You are running into a KeyError because either:

  1. You aren't putting a SECRET_KEY variable in your .env file.

  2. It can't find your .env file.

From what I can see from your answer, try moving your .env file from your root directory to where it will sit alongside settings.py.

Upvotes: 0

Related Questions