PostgreSQL: Using PostgreSQL with Django

This documentation is part of the Getting started guide. View the full guide here: How to get started with PostgreSQL.

👋 Welcome to the Stackhero documentation!

Stackhero provides a fully managed PostgreSQL cloud service, designed for reliability and speed:

  • Unlimited connections and data transfers for seamless scaling.
  • PgAdmin web UI included for intuitive database management.
  • Popular extensions included, such as PostGIS, TimescaleDB, and PgVector.
  • Simple, one-click updates keep your database secure and current.
  • High performance and strong security on private, dedicated infrastructure.

You can get started with Stackhero's PostgreSQL cloud hosting in just a few minutes. Enjoy a reliable database experience and save valuable time managing your data.

If it is not already installed, install the psycopg module, which will be used to connect to PostgreSQL:

pip install psycopg

In this initial step, you will store the password directly in the settings.py file. This method is only for testing because it is not secure. Later in this documentation, you will find an example of best practice.

Open the settings.py file and add the following configuration:

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.postgresql',
    'HOST': '<XXXXXX>.stackhero-network.com',
    'PORT': <PORT>,
    'OPTIONS': {
      'sslmode': 'require',
    },
    'NAME': 'admin',
    'USER': 'admin',
    'PASSWORD': '<ADMIN_PASSWORD>'
  }
}

Be careful: this example is not recommended for production and is intended for testing purposes only!

Once your connection works, you can adopt a more secure method to store credentials. The following example uses django-environ and stores credentials in a .env file.

  1. Install django-environ:

    pip install django-environ
    
  2. Open the settings.py file and modify it as follows:

    import environ
    env = environ.Env()
    environ.Env.read_env()
    
    DATABASES = {
      'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'HOST': env('STACKHERO_POSTGRESQL_HOST'),
        'PORT': <PORT>,
        'OPTIONS': {
          'sslmode': 'require',
        },
        'NAME': 'admin',
        'USER': 'admin',
        'PASSWORD': env('STACKHERO_POSTGRESQL_ADMIN_PASSWORD')
      }
    }
    
  3. Open or create the .env file in the same directory as settings.py and add:

    STACKHERO_POSTGRESQL_HOST=<XXXXXX>.stackhero-network.com
    STACKHERO_POSTGRESQL_ADMIN_PASSWORD=<ADMIN_PASSWORD>
    
  4. Finally, add .env to your .gitignore file to ensure your credentials are not stored in your Git repository:

echo ".env" >> .gitignore