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

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
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
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

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
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

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 “psycopg2” 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

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

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