Search code examples
djangodatabasedevelopment-environment

Problem with database when I use .env file


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.


Solution

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