Django is a framework developed in python and the web development using this framework makes the task simple, clear separation between view and controller. The view templates even can not insert custom codes, that is great, which separates coding from view(coding makes mess in html code)
So, creating a sample Django application and running through command is very easy which can be used for development purpose. And good thing is that, the changed code is reflected when browser is reloaded, that means we do not need to recompile the code. But what if I want to deploy to a dedicated server (I mean Apache2) ? It is not straight forward. Although there are many different possible configurations, I will focus on the basic configuration that make the website running. Later we can extend it with more and more.
So, let us begin it.
1) Virtualenv
There might be other methods also, I will explain the methods which needs creation of virtualenv. So, first of all, we need python-pip which can be installed with
sudo apt-get install pip
sudo pip install virtualenv
I normally used Eclipse IDE and for a django project I have instally PyDev plugin which makes the task easier. With eclipse I create a Django project and after you have created it , you can directly test it(Thanks Eclipse, it creates everything for you).
Now we install virtualenv inside the directory so that we can deploy the whole directory to new server without worrying the server.
So, we run the following command from inside the project folder:
virtualenv ENV
Then,
activate it
source ENV/bin/activate
2) Install Django
We can now install django module using
pip install django
So, the basic project is ready to deploy.
3) Server Preparation
a) Module wsgi
My assumption is that we already installed apache2 . That is not enough, we need to install libapache2-mod-wsgi module also.
sudo apt-get install libapache2-mod-wsgi-py3
* py3 here means python 3
Now we provide the access definition for wsgi.py file in the project.
b) apache2.conf
We write the following line in /etc/apache2/apache2.conf
<Directory /Backup/workspace/java/misc/DjangoProject>
<Files wsgi.py>
Require all granted
</Files>
c) Define site
Now, finally, we define and enable site in /etc/apache2/sites-available. We create a file 0001-python.conf (for e.g.) with the following contents:
WSGIDaemonProcess sampleapp python-path=/Backup/workspace/java/misc/DjangoProject:/Backup/workspace/java/misc/DjangoProject/ENV/lib/python3.4/site-packages
WSGIProcessGroup sampleapp
WSGIScriptAlias /sampleapp /Backup/workspace/java/misc/DjangoProject/DjangoProject/wsgi.py
And enable this site :
sudo a2ensite 0001-python.conf
sudo apt-get apache2 restart
References:
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/modwsgi/
https://www.digitalocean.com/community/tutorials/how-to-run-django-with-mod_wsgi-and-apache-with-a-virtualenv-python-environment-on-a-debian-vps