PostgreSQL: Using PostgreSQL with Django

This documentation is part of the Getting Started guide. You can view the complete guide here: How to Get Started with PostgreSQL.

👋 Welcome to the Stackhero documentation!

Stackhero offers a ready-to-use PostgreSQL cloud solution that provides a host of benefits, including:

  • Unlimited connections and data transfers.
  • PgAdmin web UI included.
  • Many modules included like PostGIS, TimescaleDB, and PgVector.
  • Effortless updates with just a click.
  • Optimal performance and robust security powered by a private and dedicated VM.

Save time and simplify your life: it only takes 5 minutes to try Stackhero's PostgreSQL cloud hosting solution!

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