Wednesday 16 December 2009

Django

(Installing on Ubuntu Karmic.)

First of all we need Apache, mod_wsgi and Django itself:

sudo apt-get install apache2
sudo apt-get install libapache2-mod-wsgi
tar -xvf Django-1.1.1.tar.gz
cd Django-1.1.1
sudo python setup.py install


I found out later that Django is packaged for Ubuntu, it's called "python-django", so I needn't have installed from source. Never mind. I'm just setting up a local server on my laptop for development, so I'd also like it to server the media files (the CSS and images) for the admin interface. So I created a symlink:

sudo ln -sT /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media/ /var/www/admin_media

We also need a bunch of additions to httpd.conf to set up Django using mod_wsgi:

sudoedit /etc/apache2/httpd.conf

Here I'm mapping "/" to serve my application, but overriding "/admin_media" to point to my media files symlink. Why did I bother with the symlink? Hmm, good question. httpd.conf:

WSGIScriptAlias / /home/weeble/hg/webtest/django.wsgi
Alias /admin_media/ /var/www/admin_media/
<Directory /var/www/admin_media>
Order deny,allow
Allow from all
</Directory>


We need to set up django.wsgi:

import os
import sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'webtest.settings'

sys.path.append('/home/weeble/hg/webtest')
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()


I had to configure a few settings for my Django application in settings.py. I'm using an sqlite database because it's easy. I have ended up with a silly directory structure here, with two nested "webtest" directories. You probably don't want to copy that. Here are the salient bits from settings.py:

DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = '/home/weeble/hg/webtest/webtest/webtest.db'
ADMIN_MEDIA_PREFIX = '/admin_media/'


Apache runs as a different user, so we need to make sure it has permission to read and write the database file, as well as to write to the directory containing the database file. I did this the bad way (I think I should probably have used chgrp or chown):

chmod o+w webtest.db
chmod o+w .


I forgot to make the directory writeable at first, and this resulted in the admin interface getting a server error whenever I visited it, as did any of my application's pages if they tried to write to the database.

Of course, you need to restart the server to pick up all the configuration changes:

sudo apache2ctl restart

No comments:

Post a Comment