WEB HOSTING SUPPORT NETWORK
     
 

Running Django with PostgreSQL

In this tutorial, we will show you how to configure a Django project on your hosting account that uses PostgreSQL as the database backend using the WebApps platform.

If you do not see a WebApps section in the Control Panel of your hosting account, this tutorial may not be suitable for your particular hosting environment. Please contact our support team for more information.

You need SSH access to the server in order to make the changes described in this tutorial. If you haven't set up SSH for your account yet, you should do this now.

Note that you should also enable both "Network tools" and "Compiling tools" on the SSH Access page of the Control Panel of your hosting account.

Quick Setup

If you want to quickly set up a Django project, you should first set up a PostgreSQL instance. We would recommend that you use the shell script from the Quick Setup section at the beginning of the article. It will configure PostgreSQL and it will set up the environment of your hosting account for installing Django.

After PostgreSQL is running in your account, you can download this Django setup shell script to your account and run it. The script will set up the WebApps project for your Django site.

Note that the Django setup script will automatically configure the PostgreSQL login details for your Django application, so you don't have to do this manually. You can simply run the two scripts in sequence:

# Set up PostgreSQL
setup_postgresql.sh

# This sets up $PGHOST in the shell environment
. ~/.bashrc

# Set up Django
mv 4867.sh setup_django.sh
chmod 755 setup_django.sh
./setup_django.sh

In that case, you can skip to the "Running the Django Website" section of this article.

Installation

Before you start the installation, you have to make sure that you have a running instance of PostgreSQL in your account and that the $PGHOST environment variable is set in your shell. There is more information about this in the Running a PostgreSQL Instance article. The quick setup script can take care of that for you.

After that, you can create the directory structure of your new Django site:

sureapp_project="django1"
django_project_dir="/home/$USER/private/$sureapp_project"
mkdir -p "$django_project_dir/sureapp"

Then, set up the database details:

[ -z "$PGHOST" ] && . /home/$USER/.bashrc
if [ -n "$PGHOST" ]
then
    pguser="$sureapp_project"
    pgpass="$(pwgen 24 1)"
    pgdb="${sureapp_project}_db"
    printf "CREATE ROLE %s PASSWORD '%s' NOSUPERUSER NOCREATEDB NOCREATEROLE INHERIT LOGIN;" "$pguser" "$pgpass" | psql postgres
    createdb --owner "$pguser" "$pgdb" && printf "Database %s created successfully.\n" "$pgdb"
fi

virtualenv

For Python applications like Django, it is common to create an isolated environment for the application. You can do this with virtualenv:

mkdir -p "/home/$USER/.local/bin"
grep -q '^PATH=.*/.local/bin' "/home/$USER/.bashrc" || printf '\nPATH="/home/%s/.local/bin:$PATH"\nexport PATH\n' "$USER" >> "/home/$USER/.bashrc"
PATH="/home/$USER/.local/bin:$PATH"
export PATH
pip3 install virtualenv
virtualenv --system-site-packages -p /usr/bin/python3 "$django_project_dir/venv"
. "$django_project_dir/venv/bin/activate"

This way, all Python dependencies will be used only by your site.

Python Dependencies

You can now continue to installing the software dependencies of your Django site.

pip3 install psycopg2 whitenoise gunicorn Django
  • psycopg2 is a PostgreSQL database adapter;
  • whitenoise is a static files server, particularly suitable for Django;
  • gunicorn is a robust and performant WSGI server for production use;
  • Django is the package that contains the Django framework.

Django Project

At this point, you can set up the Django project and configure it:

django-admin startproject "$sureapp_project" "$django_project_dir"
django_project_settings_file="$django_project_dir/$sureapp_project/settings.py"
sed -i 's/^DEBUG = .*/DEBUG = False/' "$django_project_settings_file"
sed -i "s/^ALLOWED_HOSTS = .*/ALLOWED_HOSTS = ['*']/" "$django_project_settings_file"
cat <<POSTGRES_CONFIG >> "$django_project_settings_file"
DATABASES['default'] = {
    'ENGINE': 'django.db.backends.postgresql',
    'NAME': '$pgdb',
    'USER': '$pguser',
    'PASSWORD': '$pgpass',
    'HOST': '$PGHOST',
}
POSTGRES_CONFIG
cat <<STATICFILES_CONF >> "$django_project_settings_file"
import os STATIC_ROOT = os.path.join(BASE_DIR, 'static') MIDDLEWARE.append('whitenoise.middleware.WhiteNoiseMiddleware') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_CONF python3 "$django_project_dir/manage.py" migrate python3 "$django_project_dir/manage.py" collectstatic

Creating the WebApps Project

Here, you have to create the WebApps project. This is necessary because it will determine the port on which your Django application will listen for requests.

sureapp project create \
    --engine "custom" \
    --engine-version "-" \
    --release-dir "$django_project_dir/sureapp" \
    --start-cmd "$django_project_dir/start.sh" \
    "$sureapp_project"

WSGI Server

Gunicorn is a robust and performant WSGI server meant for production use.

The easiest way to start the WSGI server is to use a wrapper shell script:

wsgi_port="$(sureapp project list | grep "$sureapp_project" | awk '{print $5}')"
cat <<START_SH > "$django_project_dir/start.sh"
#!/bin/sh
cd "$django_project_dir"
. "$django_project_dir/venv/bin/activate"
exec gunicorn -b "127.0.0.1:$wsgi_port" -w 4 "$sureapp_project.wsgi:application"
START_SH
chmod 0700 "$django_project_dir/start.sh"

Running the Django Website

WebApps Project

You now have to complete the configuration of the WebApps project in order to set up the URL where the application will be accessible.

The WebApps project is already created, so you have to click on the "Edit" icon in order to modify its settings:

apps_list-edit.png

You should set up the domain and subdomain fields:

edit_app-url.png

If you want to put your Django application on a separate subdomain, you can create one on the Subdomains page of the Control Panel.

Finally, you have to enable the application to run it:

edit_app_saved-enable.png

Management Script

Although it is not required, it is convenient to create a simple wrapper script to make managing the Django application from the command line easier. This script will take care of setting up the environment for you so that you don't have to do it every time you want to use the manage.py script in the installation directory of Django.

cat <<MANAGE_SH > "$django_project_dir/manage.sh"
#!/bin/sh
. "$django_project_dir/venv/bin/activate"
exec python3 "$django_project_dir/manage.py" "\$*"
MANAGE_SH
chmod 0700 "$django_project_dir/manage.sh"
ln -s "$django_project_dir/manage.sh" "/home/$USER/.local/bin/manage-$sureapp_project"

With this wrapper script, you can log in over SSH and directly run any command in your Django project. For example, assuming that you named the project django1 as in this example, you can use the following command to see what management options are available:

manage-django1 help

Logging In

The installation script creates a wrapper shell script that allows you to manage your Django project directly on the command line, without having to first activate the virtualenv environment separately.

For example, you can create an administrative username for your Django project like this (assuming the project is named django1):

manage-django1 createsuperuser

After you fill out the prompts, you will be able to log in as the administrator of your new Django website.