Search code examples
postgresqldocker-composedockerfilepsycopg2django-postgresql

Django in connection with Postgres says settings.DATABASES is improperly configured


I am so new to Django and postgresql. Django made a connection at first step and created my tables, but after that just keep telling 'settings.DATABASES is improperly configured, Please supply the NAME or OPTIONS['service'] value.'. I really don't know what is the issue. I will post some of code related to database. my database is running and I can see my tables there via pgAdmin. Django version is 4.1.4 and psycopg2 version is 2.9.5.

Exception:

Exception Type: ImproperlyConfigured at /accounts/login
Exception Value: settings.DATABASES is improperly configured. Please supply the NAME or OPTIONS['service'] value.

My settings.py


POSTGRES_HOST = os.environ.get('POSTGRES_HOST', default="")
POSTGRES_DB = os.environ.get('POSTGRES_DB', default="")
POSTGRES_USER = os.environ.get('POSTGRES_USER', default="")
POSTGRES_PASSWORD = os.environ.get('POSTGRES_PASSWORD', default="")

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': POSTGRES_DB,
        'USER': POSTGRES_USER,
        'PASSWORD': POSTGRES_PASSWORD,
        'HOST': POSTGRES_HOST,
        'PORT': 5432,
    }
}

My docker-compose.yml

version: "3.11"

x-service-volumes: &service-volumes
  - ./:/app/:rw,cached

x-database-variables: &database-variables
  POSTGRES_DB: postgres
  POSTGRES_USER: postgres
  POSTGRES_PASSWORD: postgres

x-app-variables: &app-variables
  <<: *database-variables
  POSTGRES_HOST: postgres

services:
  website:
    image: myproject-website:latest
    command: python3 manage.py runserver 0.0.0.0:8000
    volumes: *service-volumes
    depends_on:
      - db_migrate
    ports:
      - "8000:8000"

  db_migrate:
    image: myproject-website:latest
    command: python3 manage.py migrate
    volumes: *service-volumes
    environment: *app-variables
    depends_on:
      - postgres
  
  postgres:
    image: postgres
    ports:
      - "5432:5432"
    environment: *database-variables
    volumes:
      - db-data:/var/lib/postgresql/data

volumes:
  db-data:

I checked both project and database is running in docker and is listening to new connections. I tried to put real values as default values, like below: POSTGRES_DB = os.environ.get('POSTGRES_DB', default="postgres") and it didn't work either.


Solution

  • I needed to change docker-compose.yml in website part like below:

    services:
      website:
      image: myproject-website:latest
      command: python3 manage.py runserver 0.0.0.0:8000
      volumes: *service-volumes
      depends_on:
        - db_migrate
        - postgres
      environment: *app-variables
      ports:
        - "8000:8000"