90% OFF ALL NEW PLANS TO HELP MORE BUSINESSES MOVE ONLINE

Installing Django [version 2.1.3]

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

If you do not have a Web Apps section in your hosting Control Panel, then this tutorial is not suitable for your particular hosting environment. You can ask your hosting provider for more information, or you can seek assistance through our ticketing system.

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.

1. The first step is to create a directory for Django in the private directory on your account

  • Web apps can only be deployed in directories in the private directory on the account. We recommend that you create a separate directory there for the app to avoid mixing its contents with other apps or other files in the private directory. You can create the directory using the File Manager in your hosting Control Panel. In this example, the directory is called "django".

2. Create the app using the Web Apps section of the hosting Control Panel

  • 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. Installing Django

  • 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

  • Through your hosting Control Panel > SSH Access section > Additional tools, make sure that the "Compiling tools (gcc, g++)" feature is enabled.
  • On our servers, Python 2 is the primary Python interpreter, so "python" and "pip" commands use Python 2 by default. The latest version of Django requires Python 3. The path to Python 3 is /usr/bin/python3. The alias for this binary is "python3". You can add aliases to /home/myusername/.bashrc
  •  Your next step is to install Django. It is time to use Sureapp - our app management CLI tool. Enter the shell of your web app with the following command (replace Django with the name of your web app):

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 with the following command:

myusername@s501 [django:custom/-] /home/myusername/private/django$ pip3 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.
  • 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 -p /usr/bin/python3 /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 commands in the /home/myusername/private/django/django1 directory:

(django1) myusername@s501 [django:custom/-] /home/myusername/private/django/django1$ pip3 install Django
(django1) myusername@s501 [django:custom/-] /home/myusername/private/django/django1$ pip3 install mysqlclient

  •  Run the following command:

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

4. Setting up Django to use MySQL instead of SQLite

  • 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 here. 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:

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

  • 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': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}

  • 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$ python3 manage.py migrate

  • 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$ python3 manage.py createsuperuser

  •  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 and check that the site is working as you expect at http://www.mydomain.com/admin/

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

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

5. Getting ready for production - Gunicorn+WhiteNoise or uWSGI

5.1. Gunicorn and WhiteNoise
  • Gunicorn is a Python WSGI HTTP server recommeded 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$ pip3 install whitenoise
(django1) myusername@s501 [django:custom/-] /home/myusername/private/django/django1/mysite$ pip3 install gunicorn

 install-gunicorn-and-whitenoise.png

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

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 its 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',
]

  • You should also update the ALLOWED_HOSTS setting in settings.py, so it looks like so:

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

  • 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 Web Apps 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

  • You can visit http://www.mydomain.com/admin to make sure that Django is running as expected.
5.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$ pip3 install uwsgi

  • Update the ALLOWED_HOSTS setting in /home/myusername/private/django/django1/mysite/mysite/settings.py:

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

  • 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 > Web Apps 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.
  • You can visit http://www.mydomain.com/admin to make sure that Django is running as expected.

django-admin.png