Search Here

Deploy Django Web Application to Apache Server

Deploy Django Web Application to Apache Server Step by Step Guide

In this post, you’ll learn step by step to Deploy Django Web Application to Apache Server Step by Step Guide.

Table of Contents

Introduction

Django Deployment requires some configuration to be done in an apache server. In this post, we’ll guide you in creating a Django app and deploying it to the server.

Note

Instructions in this post are for Ubuntu users. You can also visit official Django Installation by clicking here

Install Libraries

First, make sure you have installed Python. You can find out python version by opening terminal and typing python –version.
We need to install some libraries to let apache and Django communicate.

  • First, use sudo apt-get update that will update existing packages in your Ubuntu System.
  • python3-pip is a package manager for python.
  • apache2 is a web server.
  • libapache2-mod-wsgi-py3 is an adapter for running python application in the apache web server.
    sudo apt-get update
    sudo apt-get install python3-pip apache2 libapache2-mod-wsgi-py3

Install Virtualenv

Virtualenv is helpful when we need to work with different Django application that uses different python versions. This avoids conflicting with other versions.

To install virtualenv type below command.

    sudo pip3 install virtualenv

Make Project Directory

Let’s start creating a directory for the project

mkdir django_projects
cd django_projects

Now you are inside django_projects directory. Within this directory create a Python virtual environment by typing below command.

virtualenv env

In directory django_projects you will find a folder env which has all python related files.

Now we have to activate env to do that type below command.

source env/bin/activate

You will get output something like this below.

(env)user:~/django_projects$  

If you see (env) than it means that env is now activated. If you want to get out then use deactivate command.

Install Django with a specific version

You can install Django using pip command. But note that you must be inside django_projects and env must be activated

(env)user:~/django_projects$  pip3 install django

To install specific Django version use pip3 install django==.
example : pip3 install django==2.2.7

Install MySQL client

This step is optional but if your project uses MySQL as database than we’ll need this.
To install MySQL client for Django type below command.

(env)user:~/django_projects$  pip3 install mysqlclient

You can also a specific which version on MySQL client you would like to install by adding equals to sign pip3 mysqlclient==.

Create a Django Project

To create a new Django app type command below command.

(env)user:~/django_projects$  django-admin startproject test_django

startproject will create a new project and test_django is a project name.

Create a Django App

After startproject command, you can find folder test_django and inside it, there will be a settings.py file which means that Django has created a project.
Now to create app go inside project root and type below command.

(env)user:~/django_projects/test_django$  django-admin startapp myapp

You can see that Django as created myapp in directory django_projects/test_django.

Migrate Django models to MySQL database

Now if you goto settings.py file there is a section DATABASES there you have to configure database settings.
For MySQL use below settings.

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'database_name',
    'USER': 'database_user_name',
    'PASSWORD': 'database_password',
    'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
    'PORT': '3306',
    'OPTIONS': {
        'sql_mode': 'traditional',
    }
  }
}

If your database does not have PASSWORD then leave it blank. Now to run your project goto project root django_projects/test_django and type below command.

(env)user:~/django_projects/test_django$  python manage.py runserver

Your response in the terminal will be like this below.

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

July 06, 2020 - 02:24:38
Django version 2.2.7, using settings 'test_django.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

To see your project in the browser go to http://127.0.0.1:8000/ and you’ll find a page like this below.
Running Django using python manage.py runserver command

If warning shows up like above-unapplied migration(s) then this is because Django has some default models such as authentication, permissions, migrations etc which must be migrated to the database.
To migrate models use below command.

(env)user:~/django_projects/test_django$  python manage.py migrate

You’ll get below message from the terminal like below.

(env)user:~/django_projects/test_django$ python manage.py migrate
    Operations to perform:
    Apply all migrations: admin, auth, contenttypes, sessions
    Running migrations:
    Applying contenttypes.0001_initial... OK
    Applying auth.0001_initial... OK
    Applying admin.0001_initial... OK
    Applying admin.0002_logentry_remove_auto_add... OK
    Applying admin.0003_logentry_add_action_flag_choices... OK
    Applying contenttypes.0002_remove_content_type_name... OK
    Applying auth.0002_alter_permission_name_max_length... OK
    Applying auth.0003_alter_user_email_max_length... OK
    Applying auth.0004_alter_user_username_opts... OK
    Applying auth.0005_alter_user_last_login_null... OK
    Applying auth.0006_require_contenttypes_0002... OK
    Applying auth.0007_alter_validators_add_error_messages... OK
    Applying auth.0008_alter_user_username_max_length... OK
    Applying auth.0009_alter_user_last_name_max_length... OK
    Applying auth.0010_alter_group_name_max_length... OK
    Applying auth.0011_update_proxy_permissions... OK
    Applying sessions.0001_initial... OK

Now you can go to the database and you’ll see that all models are migrated to tables in the database.

Setup Django Admin (using createsuperuser)

Django provides backend admin functionality out of the box. To enable this feature type below command.

(env)user:~/django_projects/test_django$  python manage.py createsuperuser

You’ll be asked to type authentication-related information such as username, email and password using these you’ll be logging to Django Administration Panel.

To login into admin panel goto URL http://127.0.0.1:8000/admin/login/ and you be shown login below like below.
Django Admin Login Page

And after you type username and password you’ll be redirected to this page like below.
Django Admin Dashboard view

Django CollectStatic files

Static Files are those CSS, images and js files and while deploying our app Django recommends to use collectstatic command and this command will create a folder in the root directory of our project and stores all our projects static files in that folder.

To set the static folder goto settings.py file and at end of document specify STATIC_URL and STATIC_ROOT.

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

Run below command to collect all the project static files into the static folder.

(env)user:~/django_projects/test_django$  python manage.py collectstatic

Now exit env by typing below command.

deactivate

Start Deploying to Apache Web Server

Create and Configure the .conf file for Django App

To configure the Apache Web Server to host our Django app we’ll create a virtual host file by below command.

sudo nano /etc/apache2/sites-available/testdjango.conf

and to tell apache webserver about location of our Django project add below content to file.

<VirtualHost *:80>
    ServerAdmin admin@testdjango.localhost
    ServerName testdjango.localhost
    ServerAlias www.testdjango.localhost
    DocumentRoot /home/django_projects/test_django
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    Alias /static /home/django_projects/test_django/static
    <Directory /home/django_projects/test_django/static>
        Require all granted
    </Directory>

    Alias /static /home/django_projects/test_django/media
    <Directory /home/django_projects/test_django/media>
        Require all granted
    </Directory>

    <Directory /home/django_projects/test_django>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIDaemonProcess django_project python-path=/home/django_projects/test_django python-home=/home/django_projects/test_django/env
    WSGIProcessGroup django_project
    WSGIScriptAlias / /home/django_projects/test_django/wsgi.py
</VirtualHost>

test_django.conf contains all the details of our projects location and static folders.

Enable Virtual Host

After this, we must enable our newly created host to do that use below command.

cd /etc/apache2/sites-available
sudo a2ensite testdjango.conf

Adding the project URL to host file

127.0.0.1 testdjango.localhost

We’ll access our app using url testdjango.localhost.

Resolving Permissions for accessing the Django app.

sudo ufw allow 'Apache Full'

Allows apache to access Django application out of its scope.
Other Permissions related to database and project

sudo chown :www-data /home/django_projects/test_django/

To check whether all the above steps are correct and have no syntax errors type below command.

sudo apache2ctl configtest 

Below output will be displayed.

Syntax OK

Configuring Django Apps settings.py File

We must add testproject.localhost to ALLOWED_HOSTS in Django settings.py file.

ALLOWED_HOSTS = ['testproject.localhost']

Restart Apache Web Server

You may find your Django app not displaying in the webpage for this you need to restart the apache web server.

sudo service apache2 restart

Now if you goto URL testproject.localhost it will display your Django app.

Conclusion

So we have come to the conclusion part of our Deploy Django Web Application to Apache Server Step by Step Guide.
If you like this then please share and for queries comment below. We’ll reach to you soon.

Related Posts

Summary
Review Date
Reviewed Item
Deploy Django Web Application to Apache Server Step by Step Guide
Author Rating
51star1star1star1star1star
Software Name
Django Web Framework
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Developmen