How to Start Django Project with a Database(PostgreSQL)

stackpython
8 min readAug 6, 2020

--

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 you guys have no experience with Django beforehand, knowledge of Python programming is required

Software and Tools

In this article I use Windows, no problem if you guys use others like Mac or Linux, only some commands are slightly different, so I think this is not a problem, you can search Google to find those

Let’s get started !!

1. Create a 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 virtual environment, so you’ve to run the command below
env/scripts/activate

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

Complete this process (Virtual Environment) now

2. Install Django

After successfully creating the directory and virtual environment, it’s time to install Django

pip install django
pip freeze

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

To see which pagekages are installed

3. Open a desired IDE or Text Editor

Open an IDE or text editor you 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”
  • Click “Open folder” to import the directory we created beforehand into VisualStudio Code workspace
  • Then open the terminal, because it’s more convenient to run the code in the same terminal

So it’s time to activate virtual environment in VisualStudio Code

env/Scripts/activate
  • Hit enter, now we already activated virtual environment.

4. Start the Django project

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

django-admin startproject postgresTest

I successfully created project called “postgresTest”

My Django project

5. Start Django app

  • In VisualStudio Code terminal, you’ve to point to the project directory using “cd” command
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 types of data you want to store in your database.

  • Run the server to make sure that everything is okay
python manage.py runserver
No problem

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

6. Setting up a database server

I assume you already download PostgreSQL, if don’t, the following is the link to download → PostgreSQL downloads

  • Open pgAdmin4
  • Click server, and choose PostgreSQL version, in this article, I use version 9.6

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

Choose your PosgreSQL version
  • Then create our database name
Create a database
  • Define the database name, 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 have no tables yet.
dbtest (my database)

7. Get back to our code to config the database

I will switch from database GUI to my code again

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

This is the default database (SQLite3) that Django automatically provides us

. . .

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

. . .

If you use SQLite, you 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 I’m looking for, the professional one I need is PostgreSQL “The most recommended database for Django”

Copy the code below, then change it to your corresponding parameters

  • NAME → Database name e.g. dbtest 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': 'your_db_name',
'USER': 'postgres',
'PASSWORD': 'your_db_password',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}

Remember: Don’t keep sensitive data in the setting file, instead, use the environment variable AKA .env file

Environment Variable

As previously mentioned, any secret or sensitive data should be kept as environment variables instead of hardcoded in the settings.py file.

How?

We use django-environ package to manage .env in Django, let’s install it

Big thanks for djangocentral.com for a really informative article

pip install django-environ

pip freeze

asgiref==3.5.2
backports.zoneinfo==0.2.1
Django==4.1.2
django-environ==0.9.0 # This
psycopg2==2.9.4
sqlparse==0.4.3

Now django-environ version 0.9.0 (latest version) was installed already, then create .env file to store environment variables

.env

SECRET_KEY=django-insecure-728k0bs%91o$^sp%aa_ji@2fmtwpdk7r1na#*$%l2+%)7tnpo3
DB_NAME=your_db_name
DB_USER=your_db_user
DB_PASSWORD=your_password
DB_HOST=localhost
DB_PORT=5432

In the base or root directory, add .gitignore to not push .env file into our Git repo, also the files or directories following:

  • db.sqlite3 (SQLite database file)
  • /env (virtual environment folder)
  • *.env (all of .env files inside our project)

.gitignore

*.pyc
__pycache__
db.sqlite3
/env
*.env
.vscode
Add “.env” and “.gitignore” files

The final version of settings.py should look like this

import environenv = environ.Env()
environ.Env.read_env()
...
# Your secret key
SECRET_KEY = env("SECRET_KEY")
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': env("DB_NAME"),
'USER': env("DB_USER"),
'PASSWORD': env("DB_PASSWORD"),
'HOST': env("DB_HOST"),
'PORT': env("DB_PORT"),
}
}

8. Create a table

Get back to app in testdb/models.py

  • Create a table by writing a class/object(ORM) to access the database instead of writing raw SQL (Django automatically converts Python class/object code to be raw SQL under the hood

This is just a simple table for testing

blog/models.py

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

9. Migrate the table to the PostgreSQL database

Now, we have successfully written our tables but they aren’t being sent to PostgreSQL yet. So, let’s do “makemigrations” and “migrate”

  • makemigrations → To update database models (We have to run this command every time when something changes in models.py e.g. adding a new table, changing a field name, etc
  • migrate → The last step to submit or sent out our table into the database server

Now it’s time to run “makemigrations” command

python manage.py makemigrations

I got this error “No changes detected” because I didn’t register my app

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

No problem with the app, but I got new error “No module named psycog2

No module named ‘psycog2’

The problem with this error is I haven’t installed a library called “psycopg2” This is the database connector making Django and PostgreSQL able to talk to each other

Let’s install psycopg2

pip install psycopg2

For macOS 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 everything is okay, so I 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 pgAdmin.
  • Now I’ve successfully created my PostgreSQL database and migrated all tables in my Django project to PostgreSQL

Django generates 10 default tables e.g. user, session, permission, etc. And the last one is my app table “testdb_teacher” table

Browse to our teacher table to check everything works well

  • Right click → View/Edit Data → All Rows

It’s empty now, because I didn’t submit any data into this table. It’s out of this tutorial scope

teacher table

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

Conclusion

What you’ve learned in this article are

  • Creating a 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 migration process
  • Browsing our data in our database in pgAdmin

Looking for reliable cloud hosting for your Django project? I’ve been using🔥 DigitalOcean for all my websites and client projects for nearly 6 years. It offers easy integration with PostgreSQL, perfect for scaling applications. Plus, their customer support is among the best I’ve experienced, always there when I need assistance. Sign up to get started with $100 in free credits!.

Contact me or feel free to be a friend to share knowledge

This’s my IG: sonny_stp

--

--

stackpython
stackpython

Responses (26)