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, andPgVector.- 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.
-
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