This tutorial will show you how to install and configure Django in a Python virtual environment within a WebApp.

If you do not have a WebApps section in your hosting Control Panel, then this tutorial is not suitable for your particular hosting environment. You can submit a support ticket through our ticketing system if you need assistance.

We will set up a Django production environment. We will use Python 3, pip 3, Django, virtualenv, Python's MySQL client (mysqlclient), WhiteNoise, Gunicorn, and uWSGI in order to provide you with the tools necessary for running web applications with Django.

Prerequisites:

  • Enable SSH Access to your account.
  • Enable the Compiling tools option for your account

Both of these actions can be performed through the SSH Access section of the hosting account's Control Panel.

 

1. Create a directory for Django

To start, you will need to create a directory for your Django project. You can create the directory using the File Manager in your hosting Control Panel. In this example, we will create directory called "django". This directory needs to be created in the /private directory on your account.

  • We recommend that web apps be only deployed in directories in the private directory on the account. You should create a separate directory there for the app to avoid mixing its contents with other apps or other files in the private directory.

 

2. Create a WebApp for Django

Next, you need to create a WebApp for your Django project. Running Django as a WebApp allows the application supervisor on the server to manage the application. You can create a WebApp for Django using the WebApps section of the hosting Control Panel as follows:

  • Choose Custom as engine.
  • Enter a name for your app. It is only for internal reference to the app. In this example, it is Django.
  • Choose a subdomain at which you wish to access the app. In this example, we choose the "www" subdomain: www.mydomain.com.
  • Enter the web access path. For example, if you enter /django, you will be able to access the app at http://www.mydomain.com/django. You do not need to create the directory. In this example, we enter / (forward slash) as web access path, so the app is accessible at http://www.mydomain.com.
  • The port will be assigned automatically. It will be transparent to your users. You can see the port in the apps list after creating the project. We use 10101 as automatically assigned port in our example.
  • Select the deployment directory. Enter the directory you created in step 1 (/private/django).
  • We will add the start command of the web app once Django is fully configured.

Create a new web app

3. Install Django

It is now time to install the packages required for your Django project. To do so, follow these steps:

  • Connect to your account via SSH. You can check our online documentation for more information on doing this:

Logging Into Your Account via SSH using Putty
Logging Into Your Account via SSH using Terminal in Mac OS

  •  Use sureapp - our app management CLI tool to Enter the shell of your WebApp. Please use the following command (replace "Django" with the name of your WebApp):

myusername@s501:/home/myusername$ sureapp project shell Django

  • Next, run the following command to add a new executables path for this particular project:

myusername@s501 [django:custom/-] /home/myusername/private/django$ echo "" >> /home/$USER/.bashrc ; echo "# Additional executables path" >> /home/$USER/.bashrc ; echo "export PATH=$HOME/.local/bin:\$PATH" >> /home/$USER/.bashrc ; . /home/$USER/.bashrc

  • Install virtualenv. virtualenv is a virtual environment where you can install software and Python packages in a contained space, which isolates the installed software and packages from the rest of your account's global environment. Multiple virtual environments allow you to run various apps using different versions of software and packages, thus avoiding potential conflicts. You can install it with the following command:

myusername@s501 [django:custom/-] /home/myusername/private/django$ pip install virtualenv

  • Create a new directory, which we will use as a home for our virtual environment. In this example, we will use /home/myusername/private/django/django1
  • Set up the new virtual environment with the command below:

myusername@s501 [django:custom/-] /home/myusername/private/django$ virtualenv /home/$USER/private/django/django1

  • Activate the newly created environment:

myusername@s501 [django:custom/-] /home/myusername/private/django$ source django1/bin/activate

  • You will know the virtual env is activated by the new prefix (django1):

 activate-django1-virtualenv.png

  • Install Django and Python's MySQL client. Run the following commands in the /home/myusername/private/django/django1 directory:

(django1) myusername@s501 [django:custom/-] /home/myusername/private/django/django1$ pip install Django
(django1) myusername@s501 [django:custom/-] /home/myusername/private/django/django1$ export MYSQLCLIENT_CFLAGS=-I/usr/local/mysqlX/include MYSQLCLIENT_LDFLAGS="-L/usr/local/mysqlX/lib -lperconaserverclient"
(django1) myusername@s501 [django:custom/-] /home/myusername/private/django/django1$ pip install mysqlclient

  •  You will have to replace "mysqlX" with "mysql5" (if you connect to a MySQL5 database) or "mysql8" (if you connect to a MySQL8 database).
  •  Run the following command:

(django1) myusername@s501 [django:custom/-] /home/myusername/private/django/django1$ django-admin startproject mysite

 

4. Set up Django to use MySQL

 By default, Django is configured to use SQLite for its database engine. In order to use MySQL with your Django application, you will need to follow these steps:

  • Create a new MySQL database via the MySQL Databases section in your hosting Control Panel. It is recommended that you create a separate database user, too. More information can be found in our MySQL Databases article. In our example, we use myusername_databasename as database name, djangouser as database username, and djangodbpassword as password.
  • Using the File Manager in your hosting Control Panel, or by using your favorite command line text editor (e.g. nano), open /home/myusername/private/django/django1/mysite/mysite/settings.py for editing. Find the following block of code there:

DATABASES = {
 'default': {
 'ENGINE': 'django.db.backends.sqlite3',
 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
 }
}

  • Comment (or delete) the above lines and add the following instead (port 3306 for MySQL5 and port 3308 for MySQL8):

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'myusername_databasename',
'USER': 'djangouser',
'PASSWORD': 'djangodbpassword',
'HOST': 'localhost',
'PORT': '3308',
}
}

  • Replace the database connection settings with your own database name,  username, and password. To use MySQL's Strict Mode, which is strongly recommended by Django, you could also specify the MySQL mode:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'myusername_databasename',
'USER': 'djangouser',
'PASSWORD': 'djangodbpassword',
'HOST': 'localhost',
'PORT': '3308',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}

    • Update the ALLOWED_HOSTS settings as well:

ALLOWED_HOSTS = ['localhost','mydomain.com','www.mydomain.com']

  • navigate to /home/myusername/private/django/django1/mysite and run the command below, so the necessary data is migrated to your database:

(django1) myusername@s501 [Django:custom/-] /home/myusername/private/django/django1/mysite$ python manage.py migrate

 

5. Create an administrator user for Django

In order to access the Django administration interface, you will need to create an administrator user for Django.

  • With the next command, you can add an administrator user, so you can access the Django administration interface:

(django1) myusername@s501 [Django:custom/-] /home/myusername/private/django/django1/mysite$ python manage.py createsuperuser

 

6. Run a development server

Congratulations! You have successfully installed Django and set it up to use a MySQL database in "STRICT_TRANS_TABLES" sql mode. Run the development web server with the following command:

(django1) myusername@s501 [Django:custom/-] /home/myusername/private/django/django1/mysite$ python manage.py runserver 0:10101

  •  In the command above, make sure to replace port 10101 with the port assigned to your web app.

You can now check whether the site is working as you expect at http://www.mydomain.com/admin/.

 

7. Using Gunicorn+WhiteNoise OR uWSGI - Getting ready for production

In order to have the Django content served, you will need to use some sort of web server. In our environment, this can be done by using Gunicorn or uWSGI.

 

7.1. Gunicorn and WhiteNoise

  • Gunicorn is a Python WSGI HTTP server recommended for use with Django on our servers. To use it with your "django1" project, enter your project's shell using the Sureapp CLI tool and activate your virtual environment as explained in the steps outlined above. Furthermore, as Django does not support serving static files in production, you can integrate the WhiteNoise project into your Django application:

(django1) myusername@s501 [django:custom/-] /home/myusername/private/django/django1/mysite$ pip install whitenoise
(django1) myusername@s501 [django:custom/-] /home/myusername/private/django/django1/mysite$ pip install gunicorn

  • Add the following lines in the end of /home/myusername/private/django/django1/mysite/mysite/settings.py:

import os
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

  • Additionally, right after the first line in the MIDDLEWARE section, add

'whitenoise.middleware.WhiteNoiseMiddleware',

  • so it looks like so:

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

  • On a production site, make sure to disable DEBUG mode in settings.py:

DEBUG = False

  • As a last step before starting your app, run the following command, so the static files are copied to your project's root:

(django1) myusername@s501 [django:custom/-] /home/myusername/private/django/django1/mysite$ ./manage.py collectstatic

  • Log in to your hosting Control Panel and navigate to the WebApps section. Click the Edit button for your web app and enter the following as start command:

source /home/myusername/private/django/django1/bin/activate && cd /home/myusername/private/django/django1/mysite && gunicorn mysite.wsgi

  • Click the Update button to save the changes, and then click the red circle to enable the web app. Click the Refresh button to check if the web app was successfully enabled.

Django up and running

7.2. uWSGI - an application server container recommended for use with Django

  • Instead of installing Gunicorn and WhiteNoise, you can just install and run your application via uWSGI. To install uWSGI, run the following command:

(django1) myusername@s501 [django:custom/-] /home/myusername/private/django/django1$ pip install uwsgi

ALLOWED_HOSTS = ['localhost','mydomain.com','www.mydomain.com','DEFAULT_IP_ADDRESS']

  • On a production site, make sure to disable DEBUG mode in settings.py:

DEBUG = False

  • As a last step before starting your app, run the following command, so the static files are copied to your project's root:

(django1) myusername@s501 [django:custom/-] /home/myusername/private/django/django1/mysite$ ./manage.py collectstatic

  • Create /home/myusername/private/django/django1/uwsgi.ini and add the code below to it (the following is an example setup, and settings can be modified as needed):

[uwsgi]
chdir=/home/myusername/private/django/django1/mysite
home=/home/myusername/private/django/django1
http-socket=:10101
module=mysite.wsgi:application
die-on-term = true
master=1
vacuum=1
max-requests=5000
processes=8
threads=4
static-map=/static=/home/myusername/private/django/django1/mysite/staticfiles

  • You will have to update at least the chdir, home, static-map, and http-socket options, so the proper port and paths are defined.
  • In your hosting Contol Panel > WebApps section, edit your web app and add the following as start command:

source /home/myusername/private/django/django1/bin/activate && uwsgi /home/myusername/private/django/django1/uwsgi.ini

  • Click the Update button to save the changes, and then click the red circle to enable the web app. Click the Refresh button to check if the web app was successfully enabled.

Django up and running

 

8. Access your Django application administration interface

You can visit http://www.mydomain.com/admin to make sure that Django is running as expected.

Django_admin.jpg