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 fully managed PostgreSQL cloud solution, designed for reliability and performance:

  • Unlimited connections and data transfers for effortless scalability.
  • PgAdmin web interface included for easy database management.
  • Popular extensions included, such as PostGIS, TimescaleDB, and PgVector.
  • Simple, one-click updates to keep your database secure and up to date.
  • High performance and enhanced security on private, dedicated infrastructure.

Save time and make your life easier: 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