Django how to set up Apache to run with virtualhost

Prerequisites

Django and python need to be already installed on the server

Set up the django environment

The first we need to do is to set up our Django environment then we need to set up a virtual environment where we can install Django. In there we will get the directory for the python bin. We need this because, in our virtualhost file, we have to map to that directory.

To do this browser to the folder where you would like to have your Django project. This will be our source directory for the python environment and the executable site-packages.

I will install it under “/var/www/html/” and I will name my Django project to “example”. This will be the source directory and you can rename it to src or whatever you prefer.

Run in console:

python3 -m venv example

if you now browser down in the directory created “/example” you wil find this directory's and files “bin include lib lib64 pyvenv.cfg share”

Now we need to install Django and create an app and that we will do by activating the virtual environment

Run in console:

source bin/activate

now you will see the virtual environment name in the console or treminal.

(example) youruser(@tempcoder:/var/www/html/example

Run in console:

python -m pip install Django

Will install the following:

Collecting Django Using cached Django-4.0.6-py3-none-any.whl (8.0 MB) Collecting asgiref<4,>=3.4.1 Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB) Installing collected packages: sqlparse, asgiref, Django Successfully installed Django-4.0.6 asgiref-3.5.2 sqlparse-0.4.2

if you get problems with the installation of Django in your virtual environment check the owner of the directory and that you have write permission.

Now we can start our Django project I will name my project to exampleproject.

Run in console:

django-admin startproject exampleproject

this will set up a new directory with some new files.

exampleproject manage.py
asgi.py init.py settings.py urls.py wsgi.py

Now it’s time to start our app, I will name mine to exampleapp and this will set up another directory with some files.

Run in console:

python manage.py startapp exampleapp

New directory

exampleapp exampleproject manage.py admin.py apps.py init.py migrations models.py tests.py views.py

Now we have everything ready to start configuring our app to run and load.

So let's start with visual code or an editor you prefer. In example/exampleproject/exampleproject we have a settings.py file this one we have to edit.

First, we need to import os

import os from pathlib 
import Path

Under INSTALLED_APPS add your app:

INSTALLED_APPS = [ 'django.contrib.admin', 
                    'django.contrib.auth', 
                    'django.contrib.contenttypes', 
                    'django.contrib.sessions', 
                    'django.contrib.messages', 
                    'django.contrib.staticfiles', 
                    'exampleapp', ]

Under TEMPLATES edit DIRS

'DIRS': [BASE_DIR / 'templates'],

Under STATIC_URL:

STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static_projects', ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

Save and exit the file. Create the static_projects folder under your base dir.

Run: python manage.py migrate Now everything should be ready to run the server but we should get this to work with apache as the server so now we need to configure the virtualhost file.

Run in console:

sudo nano /etc/apache2/sites-available/example

this will create a virtualhost file with the name example:

<VirtualHost *:80> 
    ServerName example.tempcoder.org 
    DocumentRoot /var/www/html/example/exampleproject/exampleapp 
    WSGIScriptAlias /  var/www/html/example/exampleproject/exampleproject/wsgi.py 
    # adjust the following line to match your Python path WSGIDaemonProcess
    exampleapp processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/html/example 
    WSGIProcessGroup exampleapp 

    <Directory /var/www/html/example/exampleproject> 
        AllowOverride all 
        Require all granted 
        Options FollowSymlinks
    </Directory> 
    Alias /static/ /var/www/html/example/exampleproject/static/ 
    <Directory /var/www/html/example/exampleproject/static> 
        Require all granted
    </Directory>
    Alias /media/ /var/www/html/example/exampleproject/media/ 
    <Directory /var/www/html/example/exampleproject/media> 
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/example.tempcoder.org-error.log 
    CustomLog ${APACHE_LOG_DIR}/example.tempcoder.org-access.log combined
</VirtualHost>

To enable the new virtual host file, use the a2ensite helper script which creates a symbolic link from the virtual host file to the sites-enabled directory:

Run in console:

sudo a2ensite example

Once the configuration is enabled test if the syntax is correct:

Run in console:

sudo apachectl configtest

Now restart the apache service and the changes will take effect.

Run in console:

sudo systemctl restart apache2

Edit your wsgi.py file to import os, time, traceback, signal and sys

import os import time import traceback import signal import sys
from django.core.wsgi import get_wsgi_application

sys.path.append('/var/www/html/example') sys.path.append('/var/www/html/example/exampleproject') sys.path.append('/var/www/html/example/exampleproject/exampleproject') sys.path.append('/var/www/html/example/exampleproject/exampleapp')

adjust the Python version in the line below as needed

sys.path.append('/var/www/html/example/lib/python3.9/site-packages')

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'exampleproject.settings') application = get_wsgi_application()

Save and close.

Now your domain should run Django. If you encounter some 500 internal errors on the server, you probably have some permission errors for python to run in your directory use chmod to fix permissions to the directory and files.

0
Subscribe to my newsletter

Read articles from Mikael Andersson directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mikael Andersson
Mikael Andersson

My nickname comes from my rogue in Dungeons and dragon called Krikas, my name is Mikael Andersson, born and raised in Sweden. Started early with programming as early as 10 years old, I created my first game. This was at the time when Commodore 64 and Spectravideo computers had its prime time :) Educated game developer, system developer and web programmer working as an IT engineer with responsibility for systems, applications, server operation and SQL, within laboratory environments.