Article
Django Djumpstart: Build a To-do List in 30 Minutes
Being a web developer isn't always exciting. There are lots of tedious things you end up doing over and over again: writing code to talk to a database, writing code to handle page templating, writing an administrative interface ... Sooner or later you start to wish someone would just come along and wrap up all that repetitive code in nice, integrated, reusable packages, right? Well, today's your lucky day, because someone finally has.
Say hello to Django. In this article, I'll be walking through the process of creating a simple application -- a to-do list -- with Django; this tutorial will only cover a small portion of what Django can do for you, but it'll be a good start and (hopefully) enough to whet your appetite for more.
An Integrated Web Framework
In a nutshell, Django is a rapid web development framework. Like a number of other frameworks that have been making news recently (for example, Ruby on Rails), Django is designed to take care of tedious and repetitive tasks for you, freeing you up to write interesting code again. However, unlike most of the other frameworks, Django goes a few steps further and tries to provide generic building blocks that you can stick together to accomplish common tasks (like building administrative interfaces or RSS feeds). Everyone who works to develop Django also uses the framework, so anything it can do to make our jobs easier is a candidate for inclusion.
Django started life at the Lawrence Journal-World, a newspaper which serves a small town in northeastern Kansas, growing from the need to develop full-featured web applications to meet newsroom deadlines. The Journal-World released Django under an open-source license in July 2005, after it had been under development, and in use, at the paper for a couple of years.
Django is written in Python, a modern, object-oriented programming language; that means that the applications you write with Django will be in Python, too.
Python: the Five-minute Tour
If you're used to languages like PHP or Perl, Python might look a little strange to you, but once you get to know it, it'll be like a breath of fresh air.
There are two big things you'll notice when you start using Python for the first time.
First, there aren't any curly brackets marking blocks of code; you'll more than likely indent your code inside functions, for loops, if statements and such regardless of which language you use, so Python relies on this indentation to tell it where those blocks of code begin and end.
Second, the core Python language is deliberately kept small and lightweight, with functions that might be built into the core of other languages (for example: regular expressions) instead supplied in "modules" that you can import into your programs. Python comes with a solid set of standard modules to cover a programmer's most common needs.
If you're new to Python, it'd probably be a good idea to read through the official tutorial to get a feel for the basics of the language. The official documentation for Python also includes a complete listing of all the standard modules and explanations of how to use them, so browse through that list to see what Python can do out-of-the-box.
Getting Django
Since it's written in Python, Django requires you to have Python installed before you can use it. If you're on Mac OS X or Linux, you probably already have Python installed, but if you're on Windows or if (for some strange reason) Python wasn't preinstalled on your computer, you can download it from python.org. As I write this article, the latest version of Python is 2.4.3, but version 2.5 should be released any day now; there shouldn't be any incompatibilities between the two versions, but if you're going to install Python, it's probably safest to stick with version 2.4.3 until any bugs in 2.5 have been ironed out. The only version restriction that Django imposes is a requirement that you use Python 2.3 or higher.
Once you have Python, the official Django install documentation will step you through the process of downloading and installing Django. As part of this process, you'll need to download and install a Python database adapter module for the database you'll be using. I'll be using MySQL in this article; you can download the adapter (a module called mysqldb) directly from SourceForge (at the time of publication, this package will not work with Python 2.5; you'll have to use Python 2.4.3 until the SourceForge project is updated).
Windows users should just grab the .exe version, Mac users can grab a pre-built Mac installer package from the PythonMac site, and Linux users should be able to get a pre-built package from their Linux distributor, or manually build the module using the .tar.gz download from SourceForge.
If you'd prefer to use a different database, the Django installation documentation has links to download the adapter modules for PostgreSQL and SQLite, which are the two other databases Django officially supports (support for Oracle and Microsoft SQL Server is in development, but at this point is still experimental).
Once you've got Python installed, you'll need to get set up Django itself. The official Django documentation provides good instructions for Linux and Mac users, but Windows users will have to adapt the directions slightly:
In order to open the Django tarball, use a program such as WinZip instead of tar.
You'll need to add C:\Python24 to the PATH environment variable. You can do this either through the My Computer Properties dialog, or by entering the following at the command line:
SET PATH=%PATH%;C:\Python24
Of course, this command will only affect the current command line, so you'll have to retype it every time you work with Django. Your best bet is to set the PATH variable once and for all in My Computer Properties.
There's no equivalent to sudo in Windows. To set up Django, enter the following commands:
cd path-to-django
setup.py install
After setting up Django, add the django/bin directory to the PATH environment variable. Again, you can do this once through the My Computer Properties dialog, or each time you work with Django by entering the following at the command line:
SET PATH=%PATH%;path-to-django\django\bin
Diving In
Let's explore Django by writing a simple application. "Getting things done" is a popular mantra these days, so we'll build an easy tool to help with that: a to-do list manager.
Now that you've got Django installed, simply open up a command line, navigate to the directory in which you want to keep your code, and type this command:
django-admin.py startproject gtd
That will start a new Django "project" for you; Django draws a distinction between an "application," which usually provides a specific set of features, and a "project," which is usually a collection of different applications working together on the same web site.
Running the startproject command will automatically create a new directory with the name gtd, and place a few files inside it: a blank file called __init__.py, which tells Python that the directory is a Python module; a Python script called manage.py, which contains some utilities for working with your project; a settings file called settings.py; and a URL configuration file called urls.py.

At this point, you can test that everything was set up properly by typing this command (run this from a command line, inside the "gtd" directory):
manage.py runserver
Django includes a lightweight web server for testing purposes, so you don't have to set up Apache just to work on your project. The command manage.py runserver will start it up. By default, the built-in server runs on port 8000, so you should be able to type http://127.0.0.1:8000 into your browser and see a nice page telling you that Django is working.

To stop the built-in server, press Ctrl+Break on Windows, or Ctrl+C on Mac OS X or Linux.
Now that we know Django is set up properly, we can start working on our to-do list application. Type this command:
manage.py startapp todo
This will create a directory called todo, and automatically drop in a few files for you: __init__.py, again to tell Python that the directory is a Python module; and two files for application code: models.py and views.py.

Writing Models
One of the more tedious parts of web development is laying out all the database tables you'll need, figuring out which types of columns you'll want, and working out how to get data into and out of them. Django solves these problems by letting you define "models." Django's models are just Python classes that inherit from Django's own base Model class, and they let you specify all the attributes of a particular type of object in code. The Model class knows how to translate its properties into values for storage in the database, so most of the time you don't have to think about that -- you just interact with the objects as you would in any other object-oriented language.
For this application, we'll need two models: one representing a list, and one representing an item in a list. In database terms, these models will end up being two tables: one for lists, and one for the items in those lists. Each of the list items will have a foreign key that specifies the list to which it belongs.
Let's start with the model for the list. Open up the models.py file that Django created for you, and below the line that says "Create your models here," add this code:
class List(models.Model):
title = models.CharField(maxlength=250, unique=True)
def __str__(self):
return self.title
class Meta:
ordering = ['title']
class Admin:
pass
In a moment, when we tell Django to create our database tables, the above will translate into a table called list, with two columns:
- An integer primary key column called
id(Django generates this automatically for you; you don't have to specify it explicitly). - A 250-character-wide
VARCHARcolumn calledtitle. Additionally, aUNIQUEconstraint will be created on this column, ensuring that we can't create two to-do lists with the same title.
You'll notice there's also a method in the class called __str__. This method is just like toString in Java or .NET -- whenever Python needs to show a string representation of an object, it calls that object's __str__ method. The one we've defined here will return the to-do list's title, which is probably the most useful way to represent it as a string.
The class Meta part allows us to set options that will tell Django how we want the model to behave. We can set a lot of options here, but for now we'll just let Django know we want our lists to be ordered by their titles. When Django queries the database for to-do lists, it will order them by the title column.
The class Admin bit allows us to set options for Django's automatic administrative interface, which we'll see later. The pass keyword tells Django to just use its defaults.
Now let's write the model for the items in the to-do lists. It looks like this:
import datetime
PRIORITY_CHOICES = (
(1, 'Low'),
(2, 'Normal'),
(3, 'High'),
)
class Item(models.Model):
title = models.CharField(maxlength=250)
created_date = models.DateTimeField(default=datetime.datetime.now)
priority = models.IntegerField(choices=PRIORITY_CHOICES, default=2)
completed = models.BooleanField(default=False)
todo_list = models.ForeignKey(List)
def __str__(self):
return self.title
class Meta:
ordering = ['-priority', 'title']
class Admin:
pass
This model is a little more complicated, but should be easy enough to understand. There are a couple of neat tricks we're using here that deserve a quick mention, though.
The item's priority will be stored in the database as an integer, but using the choices argument and passing it the PRIORITY_CHOICES list tells Django to only allow the values we've specified in PRIORITY_CHOICES. The PRIORITY_CHOICES list also lets us specify human-readable names that correspond to each value, and Django will take advantage of those for displaying HTML forms.
created_date will be a DATETIME column in the database, and datetime.datetime.now is a standard Python function which, as its name implies, returns the current date and time. To use this function, we need to include the line import datetime before the model's definition.
We've specified that list items should be ordered by two columns: priority and title. The - in front of priority tells Django to use descending order for the priority column, so Django will include ORDER BY priority DESC title ASC in its queries whenever it deals with list items.
Now that our models are completed, it's time to get Django to create database tables based on them. In Django parlance, this is called installing the models.