[Answered ]-Django-environ and Postgres environment for docker

1👍

You can use variable expansion in your .env file. Something like

DB_NAME=dbname
DB_USER=dbuser
DB_PASSWORD=dbpassword
DATABASE_URL=psql://$DB_USER:$DB_PASSWORD@dbhost:dbport/$DB_NAME

and then something like this in your compose file

services:
  postgresdb:
    container_name: projectname_db
    image: postgres:15
    environment:
      POSTGRES_DB: ${DB_NAME}
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    ports:
      - "127.0.0.1:5432:5432"
...

I am not exactly familiar with django-environ but this should work

0👍

Apparently, django-environ doesn’t support variable expansion (as of v0.10.0), so the way I found is to spell out the individual options instead of using env.db()

Django settings

DATABASES = {
  "default": {
     # ...
     "NAME": env("DB_NAME"),
     "USER": env("DB_USER"),
     "PASSWORD": env("DB_PASSWORD"),
  },
}

Docker Compose

version: '3.8'

services:
  # ...
  db:
    environment:
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_DB=${DB_NAME}

Leave a comment