Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 28, 2022 07:37 pm GMT

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

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

$ source virtual/bin/activate

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

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

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

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>

Your folder structure will look like this:

example/ project/    __init__.py    asgi.py    settings.py    urls.py    wsgi.py manage.py
  • 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>

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

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

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*.pycdb.sqlite3migrations/media/*

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-keyDEBUG=TrueDB_NAME=db-nameDB_USER=usernameDB_PASSWORD=your-passwordDB_HOST=127.0.0.1MODE=devALLOWED_HOSTS=*DISABLE_COLLECTSTATIC=1

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

from decouple import config, Csv  #add this to the topMODE=config("MODE")SECRET_KEY = config('SECRET_KEY')DEBUG = config('DEBUG', cast=bool)ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())

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>
  • If Postgres is installed, you'll get a response with the path to the location of the Postgres install:
> which psql/usr/bin/psql

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 psycopg2pip install dj-database-urlpip install python-decouple

Make the following changes to project/settings.py

import dj_database_urlINSTALLED_APPS = [    'application',  #new    'django.contrib.admin',    ...]# Database# https://docs.djangoproject.com/en/3.1/ref/settings/#databasesif 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)

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

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, youve 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:

CommandDescription
$ virtualenv virtualsetup virtual environment
$ source env/bin/activateactivate the virtual environment
(virtual) $ pip install djangoInstal 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 psycopg2connect database to python
(virtual) $ pip install dj-database-url
(virtual) $ pip install python-decouple
(virtual) $ pip freeze > requirements.txtpin dependancies and versions
Initialize and commit to git
(virtual) $ python manage.py runserverview 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!


Original Link: https://dev.to/karen_ngala/starting-a-new-django-project-with-postgresql-backend-2786

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To