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 straightforward database management.
- A wide range of popular extensions included, such as
PostGIS,TimescaleDB, andPgVector.- Simple, one-click updates to keep your database secure and up to date.
- Optimal performance and enhanced security on private, dedicated infrastructure.
Save time and make your life easier: it takes just 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.
-
Install
django-environ:pip install django-environ -
Open the
settings.pyfile 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') } } -
Open or create the
.envfile in the same directory assettings.pyand add:STACKHERO_POSTGRESQL_HOST=<XXXXXX>.stackhero-network.com STACKHERO_POSTGRESQL_ADMIN_PASSWORD=<ADMIN_PASSWORD> -
Finally, add
.envto your.gitignorefile to ensure your credentials are not stored in your Git repository:
echo ".env" >> .gitignore