DEV Community

Karen Ngala
Karen Ngala

Posted on

Starting a new Django Project with PostgreSQL database

Pre-reading: Tutorials you may need

This article assumes:

  1. Basic understanding of Django.
  2. Basic knowledge of how to use CLI.
  3. Basic understanding of Git.

Let's jump right into it!

First, head to your terminal and create a new folder using the mkdir command. This is the folder that will host all the work for the project you are working on.
Then cd into this folder to create a virtual environment.

1. Create a virtual environment

There are many virtual environmnet tools available.

Working within a virtual environment ensures you isolate Python installs and associated pip packages, allowing you to install and manage your own set of packages that are independent of those provided by the system or used by other projects. Depending on the virtual environment you chose to install on your machine, the command to create a virtual environment will vary.

For this use case, we will be using virtualenv.

virtual is the name of my virtual environment.

$ virtualenv virtual
Enter fullscreen mode Exit fullscreen mode

Activate the virtual environment so as to work within the virtual environment:

$ source virtual/bin/activate
Enter fullscreen mode Exit fullscreen mode

2. Install Django

You can now install Django into this dedicated workspace.

# This command will install the most recent version of django.
(virtual) $ pip install django
Enter fullscreen mode Exit fullscreen mode

To install a specific version of django, specify it as follows(replace the number after the == sign with the version you wish to install):

(virtual) $ pip install django==2.2.11
Enter fullscreen mode Exit fullscreen mode

To make collaboration easier and keep track of all packages(and their versions) you have currently in your virtual environment, pin your dependencies using the following command. This will create the file requirements.txt. You can run this command severally as you install more external packages to update the list of dependencies.

(virtual) $ pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode

3. Create django project & app

Django is organized in two major parts; project and app

  • Project - the package that represents the entire website. The project directory contains settings for the whole website. A project can have many apps. Create a project using the following command:
(virtual) $ django-admin startproject <project-name>
Enter fullscreen mode Exit fullscreen mode

Your folder structure will look like this:

example/
│
├── project/
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
│
└── manage.py
Enter fullscreen mode Exit fullscreen mode
  • App - a sub-module of a project that implements a specific functionality. For example, a website can have an app for posts and another app for payment. Create a django app using the following command:
(virtual) $ python manage.py startapp <app-name>
Enter fullscreen mode Exit fullscreen mode

A new folder will be added. Your folder structure will look like this:

example/
│
├── app/
│   │
│   ├── migrations/
│   │   └── __init__.py
│   │
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
│
├── project/
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
│
└── manage.py
Enter fullscreen mode Exit fullscreen mode

4. Create gitignore & .env files

Before adding git to your project, or before you can commit the changes you've made so far, there are some files you don't want tracked.
The .gitignore file tells git to not track these files or any changes you make to them.

example/
│
├── app/
│   │
│   ├── migrations/
│   │   └── __init__.py
│   │
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
│
├── .gitignore
├── .env
├── .env.example
|
├── project/
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
│
└── manage.py
Enter fullscreen mode Exit fullscreen mode

These are some of files you add to gitignore. You can add or omit anything. For example, I usually have a .txt file that I use for 'rough work' which I add to gitignore.

virtual/
.env
*.pyc
db.sqlite3
migrations/
media/*
Enter fullscreen mode Exit fullscreen mode

The reason for adding migrations folder in gitignore is to minimize merge conflicts and errors in production.

Your project also contains sensitive data that you do not want tracked. Data like, your django secret key or your database password. This information is stored in a .env file which is then put in the gitignore file.

When collaborating with others, create a .env.example file that contains example data that other collaborators can replace with their own values to run your project locally. This way, no one commits their environment credentials and you don't have to change the values each time you pull the project.

Contents of .env may look like this:

SECRET_KEY=generate-a-key
DEBUG=True
DB_NAME=db-name
DB_USER=username
DB_PASSWORD=your-password
DB_HOST=127.0.0.1
MODE=dev
ALLOWED_HOSTS=*
DISABLE_COLLECTSTATIC=1
Enter fullscreen mode Exit fullscreen mode

You can then reference these credentials in project/settings.py as follows:

from decouple import config, Csv  #add this to the top



MODE=config("MODE")

SECRET_KEY = config('SECRET_KEY')

DEBUG = config('DEBUG', cast=bool)

ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())

Enter fullscreen mode Exit fullscreen mode

5. Database and settings.py

The default database used by Django out of the box is SQLite. For more complex projects, you will require a more powerful database like PostgreSQL.

Some operating systems may come with potgres pre-installed, or you may need to install it

To check if you have PostgreSQL installed, run which psql command.

  • If Postgres is not installed, there appears to be no output. You just get the terminal prompt ready to accept another command:
> which psql
>
Enter fullscreen mode Exit fullscreen mode
  • If Postgres is installed, you'll get a response with the path to the location of the Postgres install:
> which psql
/usr/bin/psql
Enter fullscreen mode Exit fullscreen mode

To support postgres database, you need to install psycopg2 and two other libraries. psycopg2 is a database adapter that connects databases to python.

pip install psycopg2
pip install dj-database-url
pip install python-decouple
Enter fullscreen mode Exit fullscreen mode

Make the following changes to project/settings.py

import dj_database_url


INSTALLED_APPS = [
    'application',  #new
    'django.contrib.admin',
    ...
]



# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
if config('MODE')=="dev":
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2', #changed database from sqlite to postgresql
            'NAME': config('DB_NAME'),
            'USER': config('DB_USER'),
            'PASSWORD': config('DB_PASSWORD'),
            'HOST': config('DB_HOST'),
            'PORT': '',
        }
    }
else:
   DATABASES = {
       'default': dj_database_url.config(
           default=config('DATABASE_URL')
       )
   }

db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)


Enter fullscreen mode Exit fullscreen mode

6. Version tracking using git

Initialize version control using the git init command. Then add and commit your changes.

7. Test

Check that your set up worked by running this command:

(virtual) $ python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

You will use this command anytime you need to test your code on the browser. The default port is 127.0.0.1:8000

You should see an output like this on your browser:


At this point, you’ve finished setting up the scaffolding for your Django website, and you can start implementing your ideas by adding models, views and templates.

Summary of Commands

Commands in order of execution:

Command Description
$ virtualenv virtual setup virtual environment
$ source env/bin/activate activate the virtual environment
(virtual) $ pip install django Instal django inside virtual environment
(virtual) $ django-admin startproject <projectname> set up a Django project
(virtual) $ python manage.py startapp <appname> set up a Django app
(virtual) $ pip install psycopg2 connect database to python
(virtual) $ pip install dj-database-url
(virtual) $ pip install python-decouple
(virtual) $ pip freeze > requirements.txt pin dependancies and versions
Initialize and commit to git
(virtual) $ python manage.py runserver view website on 127.0.0.1:8000

Conclusion

In this article, we went through the steps of starting a new Django project with PostgreSQL database, as well as the common terminal commands used for Django web development.

I hope you found this article helpful!

Top comments (2)

Collapse
 
emmanuelenzeyi profile image
Emmanuel (Manu) Enzeyi

Super insightfull! All Django developers gotta read this article.

Collapse
 
karen_ngala profile image
Karen Ngala

Thank you, Emmanuel!