Skip to content

django


Connect Django to Postgres

Connecting to a postgres database:

Using insecure with user/pass in code.

DATABASES = {
    'default': {                                                                                                      
        'NAME': 'db_name',
        'USER': 'user',
        'PASSWORD' : 'password',
        'HOST': 'localhost',
    }
}

Using django-environ

  1. install django-environ
pip install django-environ
  1. create an .env file (make sure to add it to .gitignore)
SECRET_KEY=very-secret
DB_NAME=your_db_name  
DB_USER=your_db_user  
DB_PASSWORD=your_password  
DB_HOST=localhost  
DB_PORT=5432
  1. Change settings to refer to environment variables
import environenv = environ.Env()  
environ.Env.read_env()  
...# Your secret key  
SECRET_KEY = env("SECRET_KEY")  
...DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.postgresql_psycopg2',  
        'NAME': env("DB_NAME"),  
        'USER': env("DB_USER"),  
        'PASSWORD': env("DB_PASSWORD"),  
        'HOST': env("DB_HOST"),  
        'PORT': env("DB_PORT"),  
    }  
}

How to Start Django Project with a Database(PostgreSQL) | by stackpython | Medium

See also