
Want to connect your Django application to Postgresql? Well, look no further! Today, we will be discussing more on how to connect your application on any Operating System (Linux, Mac, Windows). This tutorial is used on a personal desktop, however you can follow the same steps while on a Virtual Machine (AWS EC2 or Azure).
Getting started
In order to move forward, we must download the following packages/libaries to our virtual env (or pipfile) & to our computer.
For Mac OS X:
For Windows:
For Linux:
If you want to download the package directly from the web, make sure to go to the python website.
Download Postgresl
For Mac OS X:
For Windows:
For Linux:
type the following command to make sure postgresql is installed correctly:
psql postgres
Connect to postgres remotely
Navigate to your pg_hba.conf file (Location of file is listed below)
Operating System | Location |
---|---|
Mac OS X | /usr/local/var/postgres/ |
Linux | etc/postgresql/version_num/main/ |
Windows | C:\Program Files\Postgresql\version_num\data\ |
Modify the pg_hba.conf by adding the following:
Modify 0.0.0.0/0 to your IP address if you want to add extra securityhost all all 0.0.0.0/0 md5
your pg_hba.conf should look like this:

Modify postgres.conf
Next, navigate to your postgres.conf file (Location of file is listed below)
Operating System | Location |
---|---|
Mac OS X | /usr/local/var/postgres/ |
Linux | etc/postgresql/version_num/main/ |
Windows | C:\Program Files\Postgresql\version_num\data\ |
Add the following to your postgres.conf file:
Add your IP address instead of '*' for security purposes.listen_addresses='*'
Once all files are modified, use the following command to restart your service.
For Mac OS X:
- brew services restart postgresql
For Windows:
- pg_ctl.exe restart -D C:\Program Files\Postgresql\version_num\data
For Linux:
- sudo service postgresql restart
Use the following command to ensure you can connect remotely:
psql -h ip_address -U postgres
Connect to Django project
Once successfully installed, create a new django project (skip this if you have an established project)
django-admin startproject myproject
Once completed, navigate to settings.py of your django application & replace your database information to the one below.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': ‘db_name’,
'USER': 'db_username',
'PASSWORD': 'password',
'HOST': 'db_hostname_or_ip',
'PORT': '5432',
}
}
If you need help to create a database, Click here.
Migration and runserver
Once everything is set up, use the following command to ensure the application is working fine with postgresql.
python manage.py makemigrations
Then run it on your development server
python manage.py runserver
