0

When I try to migrate some changes on one of the models I get this error but only when I use .env file in settings.py:

django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.

My settings.py

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

My .env file

# DB
DB_ENGINE=django.db.backends.postgresql
DB_NAME=db
DB_USER=user
DB_PASSWORD=password
DB_HOST=127.0.0.1
DB_PORT=5432

My Pycharm .env settings

When I set up my settings.py back to

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'db',
        'USER': 'user',
        'PASSWORD': 'password',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

I don't have any problems to migrate.

Pavel Vergeev
  • 3,060
  • 1
  • 31
  • 39
  • 1
    How are you running the migration then…? – deceze Jan 13 '23 at 10:24
  • @deceze I set up my database in settings.py back to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db', 'USER': 'user', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '5432', } } python manage.py makemigrations and python manage.py migrate and it's all good but when I switch to .env file in settings it gives an error. – Yuliyan Petrov Jan 13 '23 at 10:33
  • 1
    You do notice that you've configured your .env file specifically for the task of running the server in PyCharm? If you execute the migration via any other mechanism, the .env file isn't getting loaded. – deceze Jan 13 '23 at 10:40

1 Answers1

1

You should load the .env file inside your settings, not PyCharm.

One way to do this is to use django-environ.

Here's how you would use it in your settings.py:

import environ
import os

env = environ.Env()

# Set the project base directory
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Take environment variables from .env file
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))

# Load the environment variables
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'),
    }
}

Be sure to install the package first.

Check out the quick start or this Medium article for more examples.

Pavel Vergeev
  • 3,060
  • 1
  • 31
  • 39