Django/Apache

From Jon's Wiki
Revision as of 21:54, 29 January 2009 by Johnno (talk | contribs)

Setting up Django on Apache 2 is relatively straightforward, but with a few kinks noted herewith.

Django Requirements

  • Python >= 2.4
  • Apache 2
  • mod_python - Apache module to support Python code, similar to mod_perl
  • PostgreSQL >= 8.0
  • python-psycopg2 - PostgreSQL client library for Python
  • python-imaging - Python Imaging library
  • memcached and python-memcache (optional but reccommended)

Preparation

Django can be installed from the Debian packaged version, or fetched with SVN or with git from the Catalyst Django git mirror. and mod_python and psycopg2 can be simply installed using apt-get:

apt-get install python-django libapache2-mod-python python-psycopg2

Also, check the mod_python Apache module is enabled:

a2enmod mod_python

Example Apache VHost configuration

<VirtualHost * >
    DocumentRoot /var/www/django/clientsite
    ServerName www.clientsite.co.nz
    ServerAlias clientsite.co.nz

    # Enable mod_python handler and django config
    <Location "/">
        SetHandler python-program
        PythonHandler django.core.handlers.modpython
        PythonPath "['/var/www/django'] + sys.path"
        SetEnv DJANGO_SETTINGS_MODULE clientsite.settings
        PythonDebug Off
    </Location>

    # disable mod_python for static content - adjust as required
    <Location "/media">
        SetHandler None
    </Location>

    # some variation on the following - omit or adjust as required
    <LocationMatch "\.(jpg|gif|png)$">
        SetHandler None
    </LocationMatch>

</VirtualHost>

This config enables the mod_python handler for the root / URL, and disables it for the media subdirectory and image URLs. Features to note:

  • The PythonPath setting. Note that the path added here is the parent directory of the document root.
  • The DJANGO_SETTINGS_MODULE environment variable
  • PythonDebug - should be explicitly set to "off"

Static Content

If you are using the django admin interface from the Debian python-django package, you will need to create a symbolic link to the admin media folder in the clientsite directory, for example:

ln -s /usr/share/python-support/python-django/django/contrib/admin/media /var/www/django/clientsite/media

Alternitavely one could configure the Location directive to fetch content from the original path.

For chunky sites, have all the static content served from a separate box using a lightweight HTTP server (lighttpd).

External Links