CRUD with Django, PostgreSQL, Bootstrap and Heroku — Part 2: PostgreSQL initial setup

Carlos
3 min readMay 23, 2020

In the previous part, we made the initialization of our new project and our new app as well. Now, we have to configure our PostgreSQL database in order to be able to interact with it from Django.

For the database management, we’ll need pgAdmin. Make sure you have all the dependencies installed of PostgreSQL. This vary on each operative system, so I’d suggest you to check out how to install it on your specific OS. On this tutorial, we’ll be using PostgreSQL on Ubuntu 20.04.

Once we configured and initialized PosgtreSQL services, we go to http://127.0.0.1/pgadmin. We login with our configured credentials, and if we don’t have a server we’ll have an interface similar to the following:

We’ll create a database called “EmployeeDB”.

We hit ‘Save’, and then we’ll have the “EmployeeDB” created.

Now, we have to connect the database to our Django project. We’ll need the postgres credentials we used to create the Server.

In order to connect the database to our project, on the settings.py we need to modify the DATABASES dict.

...
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databasesDATABASES = {‘default’: { ‘ENGINE’: ‘django.db.backends.sqlite3’, ‘NAME’: os.path.join(BASE_DIR, ‘db.sqlite3’), }}
...

We should replace the sqlite3 default data with our current data of PostgreSQL.

...
DATABASES = {
‘default’: { ‘ENGINE’: ‘django.db.backends.postgresql’, ‘NAME’: ‘EmployeeDB’, ‘USER’: ‘postgres’, ‘PASSWORD’: ‘postgres’, ‘HOST’: ‘localhost’ }}
...

Now, we have to migrate our updated configuration in order to create our physical database. We can do this with the following command:

python manage.py migrate

If you get an ugly error like this:

django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named ‘psycopg2’

Don’t panic. Been there. Inside you env variable, you need to install the following dependecies:

pip install psycopg2-binary

Then, re-run python manage.py migrate and, if you’re lucky enough, you’ll get the following output:

We go back to pgAdmin, and then we should have a similar structure and schemas:

Now we’re connected locally to the PostgreSQL database from our Django project.

In the next part, we’ll start creating models on the models.py file.

--

--

Carlos

Software Developer and seldom writer. Creates technology and studies its effects on people and society.