Monday, August 15, 2011

How to Install Django on Debian using Apache mod_wsgi

Here we are going install a basic django application using apache2 mod_wsgi module. Requirements:
  • server dns: web01.dev.local
  • django code location: /usr/local/lib
  • django project: hello
Let install few packages we need:
apt-get -y install apache2 libapache2-mod-wsgi \
    python-django 
Once you ensure apache is up and running. Let create a simple django application:
cd /usr/local/lib
django-admin startproject hello
Create a /usr/local/lib/django-hello.wsgi file:
import sys
import os
import os.path

sys.path.append(os.path.dirname(__file__))
os.environ['DJANGO_SETTINGS_MODULE'] = 'hello.settings'

from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()
Add apache site configuration that will serve the django wsgi site. Add the following to /etc/apache2/sites-available/django-hello:
<VirtualHost *:80>
        ServerName web01.dev.local
        DocumentRoot /var/www/

        ErrorLog ${APACHE_LOG_DIR}/error.log
        # Possible values include: debug, info, notice, 
        # warn, error, crit, alert, emerg.
        LogLevel warn
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    
        WSGIScriptAlias / /usr/local/lib/django-hello.wsgi
        WSGIProcessGroup hello-site
        WSGIDaemonProcess hello-site processes=2 threads=16 maximum-requests=1000 display-name=apache-hello-wsgi
</VirtualHost>
Now we are going disable default apache site and enable django-hello site:
a2dissite default
a2ensite django-hello
/etc/init.d/apache2 restart
Once you navigate to http://web01.dev.local/ you should be able to see the default django welcome screen.

If you experience performance issue with content rendering, overhead of framework internal time, have a willing to fine control content caching consider take a look at the following post.

5 comments :

  1. Thanks for posting these directions. worked like a charm!

    ReplyDelete
  2. PLEASE UPGRADE THESE INSTRUCTIONS FOR DJANGO 1.4 !
    Bloody hell, why did thos f* decide to change the dir tree and location of the settings file?

    ReplyDelete
    Replies
    1. hey dude: the code is perfect for 1.4 except the django-hello.wsgi
      suppose i created django-admin.py startproject hello
      so now my django.wsgi contains:
      this is my code:
      import os
      import sys

      path = '/srv/www/hello'
      if path not in sys.path:
      sys.path.insert(0,'/srv/www/hello')
      os.environ['DJANGO_SETTINGS_MODULE'] = 'hello.settings'

      import django.core.handlers.wsgi
      application = django.core.handlers.wsgi.WSGIHandler()

      Delete
  3. As of Django 1.4, a wsgi.py file is generated by startproject, so a file like django.wsgi does not need to be created by the user anymore.
    For more details see my comment on stackoverflow (URL on my name).

    ReplyDelete
  4. Can you update the tutorial for Django 1.6 and Debian 6.0.7?
    Thanks.

    ReplyDelete