/ python

Configuring Django and Postgres

You've heard about all the benefits of node, Express, Mongo, and React. You've heard about PHP and Laravel, Golang and HTML, Ruby on Rails, and even C#, ASP.NET, and Angular. But what about poor old Python?

Django is a pretty powerful framework for building websites. It has a slew of benefits built in and you can pretty much tell it to do whatever you want. Out of the box it uses a very interesting database called SQLite. This guide is going to walk through setting up Django with PostgreSQL.

First, you'll want to make sure you have the Django and Postgres modules installed:

Once you're good to go, you can create your Django project. The name is irrelevant, the folder created assumes a placeholder, nothing more. The contents inside are what's important:

You can see that a new folder is generated, and inside the folder is another directory and a manage.py program.

You can test that everything is working by running

python manage.py runserver

and visit localhost:8000

Now that we have confirmed everything is working, it's time to get Postgres installed and configured.

You can visit this website to see how to get Postgres installed on your system. During the installation you will configure the postgres user and password. Connect to Postgres via psql and create the database.

psql -U postgres
CREATE DATABASE demodb;
\q

Head over to your appname/appname/settings.py file and make some adjustments.

Find the DATABASES section and change the values:

'ENGINE': 'django.db.backends.postgresql',
'NAME': 'yourdbname', # demodb in the example above
'HOST': 'localhost',
'PORT': '5432',
'USER': 'postgres',
'PASSWORD': 'dbpasswordyouset',

Verify everything is configured correctly by going back to your manage.py file and running:

python manage.py migrate

You can also verify it worked by going to your Postgres database:

psql -U postgres
\c demodb
\d

You can also use the \d+ table_name to view tables:

Still learning Postgres, so we'll see what the future brings ;)

I hope you enjoyed this write up.

Configuring Django and Postgres
Share this