How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 16.04

How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 16.04

How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 16.04

In this tutorial, we will walk through the steps of setting up a Django web application with Postgres as the database, Nginx as the web server, and Gunicorn as the application server on an Ubuntu 16.04 server.

Step 1: Install Required Packages

Before we begin, we need to install some packages:

sudo apt-get update sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib nginx

Step 2: Set Up Postgres Database

Next, we need to create a database for our Django application:

sudo -u postgres psql CREATE DATABASE myproject; CREATE USER myprojectuser WITH PASSWORD 'mypassword'; ALTER ROLE myprojectuser SET client_encoding TO 'utf8'; ALTER ROLE myprojectuser SET default_transaction_isolation TO 'read committed'; ALTER ROLE myprojectuser SET timezone TO 'UTC'; GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;

Step 3: Create a Python Virtual Environment

We will create a Python virtual environment for our Django project to isolate it from the system Python:

sudo apt-get install python-virtualenv mkdir ~/myproject cd ~/myproject virtualenv myprojectenv source myprojectenv/bin/activate

Step 4: Install Django and Gunicorn

With our virtual environment active, we can install Django and Gunicorn:

pip install django gunicorn psycopg2

Step 5: Create a Django Project

Now we can create a Django project:

django-admin startproject myproject ~/myproject

Step 6: Configure Django

We need to configure Django to use Postgres as the database:

nano ~/myproject/myproject/settings.py

Update the DATABASES setting:

DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'myproject', 'USER': 'myprojectuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '', } }

Step 7: Migrate the Database

We need to create the database tables:

python ~/myproject/manage.py makemigrations python ~/myproject/manage.py migrate

Step 8: Test the Django Development Server

Комментарии

Популярные сообщения из этого блога

How To Modify CSS Classes in JavaScript

How To Backup MySQL Databases on an Ubuntu VPS

How To Backup PostgreSQL Databases on an Ubuntu VPS