How to Start Django Project with a Database(PostgreSQL)

In this tutorial, I will guide you how to create a Django project, and connect to the most recommended database for Django, “PostgreSQL”

Prerequisites

  • Get familiar with Django to read or follow throughout this article understandably
  • If never use Django beforehand, knowledge of Python programming is required

Software and Tools

In this article I use Windows for OS, no problem if you guys use others like mac, linux, only some commands are slightly different, so I think this is not a problem, you can search Google to find

You don’t have to seperately install pgAdmin. Fortunately, PostgreSQL includes this for us in its package(Free)

Let’s get started !!

1. Create directory, and virtual environment

  • Create a project directory, in this case I use “django-postgres”
mkdir django-postgres
  • Point to django-postgres directory
cd django-postgres
  • Build virtual environment for the directory
python -m venv env
  • The last step is activating vitual environment, run the command below
env/scripts/activate

env is your virtual environment name, so you can name whatever name you want, for my recommendation “ Keep it short”

Complete this process (Virtual Environment) now

2. Install Django

After complete creating the directory and virtual environtment, it’s time to install Django

pip install django
pip freeze

Now, I’ve installed Django, and the lastest version of Django will automatically be installed to my project, in this case Django 3.0.8

To see which pagekages are installed

3. Open desired IDE or Text Editor

Open an IDE or text editor you love or get familiar with, e.g. PyCharm, VisualStudio Code, SublimeTex, etc

In this article I use VisualStudio Code, because it’s absolutely free, and of course you guys can follow this article without paying any cent. For my commercial project, I use PyCharmPro because it provides us everything we want, so it’s more easier to write and debug code.

Open new window on VS Code, then click “Open Folder”
  • Open folder to import the directory we created beforehand into VisualStudio Code
  • Then open VisualStudio Code terminal, because it’s more convenient to run the code in the same terminal
  • So it’s time to activate virtual environtment in VisualStudio Code
env/scripts/activate
  • Hit enter, now we already activated virtual environment.

4. Start Django project

Now it’s time to create our first project so the project will have only one project in our project directory, but we can add many apps we need

django-admin startproject postgresTest

Now you have your own project called “postgresTest”

Your django project

5. Start Django app

  • In VisualStudio Code terminal, cd to the project directory
cd postgresTest
  • Run the following command to start your first app
python manage.py startapp testdb
Django app is created

After complete building the app, then you can write your desired table that you should previously design e.g. which fields, data types you want to store in your database.

  • Now, try to run the server to check that everything is okay
python manage.py runserver
No problem

python manage.py is the command that used to run Django, so you will use it many times a long with your project

6. Setting up a database server

  • Open pgAdmin4
  • Click server, and choose PostgreSQL version, in this article, I use version 9.6
Choose your PosgreSQL version
  • Then create our database name
Create a database
  • Name the database you want, for me, I named “dbtest” for the main purpose of testing
Name the database you want
  • Now I finished creating the database. Of course in the table I haven’t had any tables yet.
dbtest (my database)

7. Get back to our code to config the database

Now, I will switch from database GUI to my code again

  • Go to settings.py
  • Approximately, in line 76 of code, this is the database config part

This is the dafault database that Django automatically provides us

. . .

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

. . .

If we use SQLite, we can immediately connect django with this database after migrating process without installing any tools or software, because SQLite stores data into a single file, no server required.

But not what we’re looking for, the professional one we need is PostgreSQL “The most recommended database for Django”

Copy the code below, then change to your corresponding database server

  • NAME → Database name e.g. dbtest that previously created in pgAdmin
  • USER → Database username (default is postgres)
  • PASSWORD → Database password
  • HOST → Database host (In development stage, use localhost or IP Address 127.0.0.1 also available)
  • PORT → The port that used to run the database (Default port is 5432)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbtest',
'USER': 'postgres',
'PASSWORD': '1234',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}

Remember: When installing PostgreSQL, you must remember, or take a note the password you filled out during installation process.

settings.py

8. Create a table

Get back to your app in testdb/models.py

  • Create a table by directly writing a class/object(ORM) to access the database instead of writing raw SQL (It should be like this)

This is just a simple table for testing

from django.db import models
# Create your models here.class Teacher(models.Model): name = models.CharField(max_length=80) age = models.IntegerField()

9. Migrate the table to PostgreSQL database

Now, we have successfully writen our table but the table isn’t being sent to PostgreSQL yet. So what we must do are the following procedures

  • makemigrations → To update and see the history or transaction happened in our table (We have to run this command everytime when something changes in models.py e.g. adding new table, change a field name, etc
  • migrate → The last step to submit or sent out our table into the database

Now it’s time to run makemigrations

python manage.py makemigrations

You will get this error “No changes detected” because you haven’t registered your app.

If you didn’t register your app
  • Go to settings.py to register the app
Registrer app

Now no problem with app, but you get new error “No module named psycog2”

No module named ‘psycog2’

The problem with this error is you haven’t installed the library called “psycog2” This is the library or database connector making Django and PostgreSQL can talk to each other

Of course, install this library via pip

pip install psycopg2

For mac if you can’t install or the above command doesn’t work, use the following command instead, just add — binary

pip install psycopg2-binary

Now I think everything is okay, so we can run makemigrations again

python manage.py makemigrations
successful makemigrations

The last step is running “migrate

python manage.py migrate
Successful migrate
  • Get back to pgAdmin
  • Double click on Tables in paAdmin.
  • Now we successfully created our PostgreSQL database, and migrate all tables in our Django project to PostgreSQL

Django generates 10 default tables e.g. user, session, permission, ect. And the last one is our table “teacher” table

Browse to our teacher table to check everything works well

  • Right click → View/Edit Data → All Rows

In teacher table, it’s empty now, because we haven’t submitted any records into this table. It’s out of this tutorial scope, of course, we will talk to in furture topics in the nex article

teacher table

Congratulations !! We’ve been successful creating our Django project with PostgreSQL

Conclusion

What we’ve learned in this article are

  • Creating virtual environment for our Django project
  • Creating Django project
  • Creating Django app
  • Running Django project
  • Playing around with pgAdmin
  • Writing a table using Django ORM without touching any SQL syntax
  • Creating and configuring our own database in PostgreSQL database
  • Setting up Django project with PostgreSQL
  • Learning about a database connector library for a specific database
  • Learning about migrating process
  • Browsing our data in our database in pgAdmin

If this article is helpful, please clap to support me continuing my good work, and do not hesitate to drop your comment below sharing me your opinion or recommendation.

Son

Full Stack Python Developers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store