Introduction
Django is a powerful web framework that can help you get your Python application or website off the ground. Django includes a simplified development server for testing your code locally, but for anything even slightly production related, a more secure and powerful web server is required.
First creating a new user
- adduser username
Grant administrative privileges
- usermod -aG username
Set up a firewall
- ufw app list
- ufw allow openSSH
- ufw enable
Switch to new user
- su username
Installing the packages
- sudo apt update
- sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib nginx curl
Login to interactive postgres session
- sudo -u postgres psql
Create a database,user for your project
CREATE DATABASE myproject;
- CREATE USER myprojectuser WITH PASSWORD ‘password’;
- 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;
- exit
Create Virtual Environment for your Project
- sudo -H pip3 install –upgrade pip
- sudo -H pip3 install virtualenv
- mkdir ~/myprojectdir
- cd ~/myprojectdir
- virtualenv myprojectenv
Activate the virtual environment
- source myprojectenv/bin/activate
Install Django
- pip install django
Create django project
- django-admin.py startproject myproject ~/myprojectdir
- nano ~/myprojectdir/myproject/settings.py
(change & add the following)
. . .
ALLOWED_HOSTS = [‘your_server_domain_or_IP’, ‘second_domain_or_IP’, ‘localhost’]
. . .
DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.postgresql_psycopg2’,
‘NAME’: ‘myproject’,
‘USER’: ‘myprojectuser’,
‘PASSWORD’: ‘password’,
‘HOST’: ‘localhost’,
‘PORT’: ”,
}
}
. . .
. . .
STATIC_URL = ‘/static/’
import os
STATIC_ROOT = os.path.join(BASE_DIR, ‘static/’)
Migrate the initial database schema to our PostgreSQL database
- ~/myprojectdir/manage.py makemigrations
- ~/myprojectdir/manage.py migrate
Create Administrative user for project
- ~/myprojectdir/manage.py createsuperuser
Collect all of the static content into the directory location
- ~/myprojectdir/manage.py collectstatic
Create an exception for port 8000
- sudo ufw allow 8000
Finally,start up the Django development server
- ~/myprojectdir/manage.py runserver 0.0.0.0:8000
In your web browser, visit your server’s domain name or IP address followed by :8000
- http://server_domain_or_IP:8000