Using Django for Scientific Web Applications

Making a Django application

We recommend to download and istall the latest official version of Django from http://www.djangoproject.com/download/. Pack out the tarfile, go to the directory, and run setup.py:

Terminal> tar xvzf Django-1.5-tar.gz
Terminal> cd Django-1.5
Terminal> sudo python setup.py install

The version in this example, 1.5, may be different at the time you follow these instructions.

Setting up a Django project

Django applies two concepts: project and application (or app). The app is the program we want to run through a web interface. The project is a Python package containing common settings and configurations for a collection of apps. This means that before we can make a Django app, we must to establish a Django project.

A Django project for managing a set of Django apps is created by the command

Terminal> django-admin.py startproject django_project

The result in this example is a directory django_project whose content can be explored by some ls and cd commands:

Terminal> ls django_project
manage.py django_project
Terminal> cd django_project/django_project
Terminal> ls
__init__.py settings.py urls.py wsgi.py

The meaning of the generated files is briefly listed below.

Django comes with a web server for developing and debugging applications. The server is started by running

Terminal> python manage.py runserver
Validating models...

0 errors found
March 34, 201x - 01:09:24
Django version 1.5, using settings 'django_project.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

The output from starting the server tells that the server runs on the URL http://127.0.0.1:8000/. Load this URL into your browser to see a welcome message from Django, meaning that the server is working.

Despite the fact that our introductory web applications do not need a database, you have to register a database with any Django project. To this end, open the django_project/settings.py file in a text editor, locate the DATABASES dictionary and type in the following code:

import os

def relative2absolute_path(relative_path):
    """Return the absolute path correspodning to relative_path."""
    dir_of_this_file = os.path.dirname(os.path.abspath(__file__))
    return dir_of_this_file + '/' + relative_path

DATABASES = {
   'default' : {
      'ENGINE': 'django.db.backends.sqlite3',
      'NAME': relative2absolute_path('../database.db')
   }
}

The settings.py file needs absolute paths to files, while it is more convenient for us to specify relative paths. Therefore, we made a function that figures out the absolute path to the settings.py file and then combines this absolute path with the relative path. The location and name of the database file can be chosen as desired. Note that one should not use os.path.join to create paths as Django always applies the forward slash between directories, also on Windows.

Setting up a Django application

The next step is to create a Django app for our scientific hello world program. We can place the app in any directory, but here we utilize the following organization. As neighbor to django_project we have a directory apps containing our various scientific applications. Under apps we create a directory django_apps with our different versions of Django applications. The directory py_apps contains the original hw.py program in the subdirectory orig, while split of this program according to the MVC pattern appears in the mvc directory.

The directory django_apps/hw1 is our first attempt to write a Django-based web interface for the hw.py program. The directory structure is laid out by

Terminal> cd ..
Terminal> mkdir apps
Terminal> cd apps
Terminal> mkdir py_apps
Terminal> cd py
Terminal> mkdir orig mvc
Terminal> cd ../..
Terminal> mkdir django_apps
Terminal> cd django_apps

The file hw.py is moved to orig while mvc contains the MVC refactored version with the files model.py, view.py, compute.py, and controller.py.

The hw1 directory, containing our first Django application, must be made with

Terminal> python ../../django_project/manage.py startapp hw1

The command creates a directory hw1 with four empty files:

Terminal> cd hw1
Terminal> ls
__init__.py models.py tests.py views.py

The __init__.py file will remain empty to just indicate that the Django application is a Python package. The other files need to be filled with the right content, which happens in the next section.

At this point, we need to register some information about our application in the django_project/settings.py and django_project/urls.py files.

Step 1: Add the app. Locate the INSTALLED_APPS tuple in settings.py and add your Django application as a Python package:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    ...
    'hw1',
)

Unfortunately, Django will not be able to find the package hw1 unless we register the parent directory in sys.path:

import sys
sys.path.insert(0, relative2absolute_path('../../apps/django_apps'))

Note here that the relative path is given with respect to the location of the settings.py script.

Step 2: Add a template directory. Make a subdirectory templates under hw1,

Terminal> mkdir templates

and add the absolute path of this directory to the TEMPLATE_DIRS tuple:

TEMPLATE_DIRS = (
    relative2absolute_path('../../apps/django_apps/hw1/templates'),
)

The templates directory will hold templates for the HTML code applied in the web interfaces. The trailing comma is important as this is a tuple with only one element.

Step 3: Define the URL. We need to connect the Django app with an URL. Our app will be associated with a Python function index in the views module within the hw1 package. Say we want the corresponding URL to be named hw1 relative to the server URL. This information is registered in the django_project/urls.py file by the syntax

urlpatterns = patterns('',
    url(r'^hw1/', 'django_apps.hw1.views.index'),

The first argument to the url function is a regular expression for the URL and the second argument is the name of the function to call, using Python's syntax for a function index in a module views in a package hw1. The function name index resembles the index.html main page associated with an URL, but any other name than index can be used.