PythonTip >> 博文 >> Django

Intro to Django - Building a To-Do List

zihua 2014-01-20 23:01:14 点击: 988 | 收藏

Django is a powerful web framework, created in Python, which follows the DRY (Don’t repeat yourself), and batteries included philosophies. It allows for rapid website development by providing a wide range of tools and shortcuts out of the box. Django is extremely fast and flexible – even faster than all of the PHP frameworks available. In this article, I’ll introduce you to Django by showing you how to build a simple to-do list.

Why Django? Why Not X?

As stated above, Django follows the batteries included philosophy. PHP frameworks such as Code Igniter try and strip all of the “unnecessaries” out for maximum performance; but Django can include all of these out of the box and still be high performance because of its modular design (If you don’t call include feature XX then it isn’t included; so it doesn’t slow the script down). Here are some of the most notable features:

  • User/Authentication system
  • Automatic RSS generation
  • GIS
  • Automatically generated Admin interface
  • Generic views (more on this later)
  • Three level caching system
  • Powerful template system
  • Comments


Django runs on an MTV (Model Template View) system (Not the television channel). This is different from MVC.

  • Model. The model sets out the schema for our database. Unlike PHP frameworks, you don’t write your queries here. Using Django’s ORM you declare the fields, field types and any additional data such as Meta information.
  • View. In the View, you set all of your code logic. You may need to pull some results from the database or manipulate some strings. The view expects a request and a response. The response is typically an http redirect, http error (404), or a call to load a template. When loading a template you usually pass some data through – most likely, results from a database query.
  • Template. The template is the plain HTML code with Django’s custom Template ‘language’ (similar to smarty) in it. You look and iterate just like you would with any other language.

Creating Our To-Do List

We are going to create a very simple application, a to-do list, to showcase how to get started with Django. We’ll use the automatically generated admin interface to add, edit and delete items. The ORM will be used to query the database. The view will pull get the to-do items and pass them onto the template where they are shown. I’m going to assume you have Django installed and running.

First, we need to create our project. To do this, we need to use the command line. startproject todo

That should have created a directory called todo. Go into that directory. (cd todo) startapp core

Yours should look similar to the image below.

Now that we have created the project, we need to input some settings. Open up todo/ with your favorite text editor. Django supports a wide range of databases – MySQL, Postgres and Oracle, to name a few. Since we are only developing, we are going to use SQLite. SQLite only requires the name of the database to be specified.

Change Line 12 to:

DATABASE_ENGINE = 'sqlite3'           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.

Change Line 13 to:

DATABASE_NAME = 'to-do.db'             # Or path to database file if using sqlite3.

With the database set up. we only need to do a couple more edits in the settings file. On line 69, we need to set a full path to the templates directory where all of our HTML templates will be stored. Create the directory in /todo/core/ and then specify it on line 69. My template directory and installed apps tuple:

Finally, we need to add our application and the admin application into the INSTALLED APPS tuple. So on line 81, insert:




That’s it for the file.


Now we need to specify our model. Open /todo/core/ with your text editor. As I said above, models define the structure of the database. There’s no need to run raw CREATE TABLE.. SQL queries, Django can do all of this for us. We just need to specify what we want. Since its a to-do list – each to-do will have a title, some content, and the date it was published. It’s very easy to represent this in Django.

from django.db import models

class todo(models.Model): #Table name, has to wrap models.Model to get the functionality of Django.
	name = models.CharField(max_length=100, unique=True) #Like a VARCHAR field
	description = models.TextField() #Like a TEXT field
	created = models.DateTimeField() #Like a DATETIME field

	def __unicode__(self): #Tell it to return as a unicode string (The name of the to-do item) rather than just Object.

Now that we have defined the database, we need to tell Django to sync all of the tables. We can do this by calling the syncdb command in the command line. Open up the command line and navigate to todo/. syncdb

You should get some output for the tables created, as well as a prompt for creating a super user. Create the user and make a note of the username and password, as we’ll use them to login to the admin area. For this tutorial we are going to use Django’s test server to test our application. It is strongly advised that you do not use the test server in deployment, but instead use apache + mod_python or FastCGI. To start the test server, we again call but with the argument of runserver. We can additionally provide a port for it to run on. By default it runs on port 8000. runserver 9090

To view the results we can go to .


Now we need to set up our URLs. Unlike PHP all URLs in Django are routed. That simply means we specify them ourselves. If a user tries to navigate to a page that isn’t set, it simply returns a 404. Since this is a simple to-do application, we only need to set one URL, the index page. We are also going to enable our admin panel so that we can add, delete and edit our to-do items.

from django.conf.urls.defaults import *
from django.contrib import admin


urlpatterns = patterns('',
    (r'^admin/(.*)',, #Lets us access the admin page
    (r'^$', 'todo.core.views.index'), #Our index page, it maps to / . Once the page is called it will look in /todo/core/ for a function called index

The final thing we need to do before we can use the admin panel is to register the model with it. Create todo/core/ and set the contents to:

from django.contrib import admin #Import the admin
from models import todo #Import our todo Model. #Register the model with the admin

Now that the URLs are set, the database is synced, and the model is registered, we can access our administrator panel. Start the test server if it isn’t already and navigate to . Login with the super user details you created.

You can see under the core heading there is “todo” – the name of the model. By clicking on this, we can see all of the “to-dos” we have made. The admin interface for making new to-dos is below.

Now that creating, updating and deleting the to-do items are finished, all we need to do is display them. If you navigate to you will see an error saying that “the view called index does not exist”. Remember – in the file, we specified that if the user visited the index, then it would load /todo/core/ with the function index()? We’re going to specify that now. We write index() just like any other Python function, except it has to accept a request and return a response.

from models import todo
from django.shortcuts import render_to_response

def index(request): #Define our function, accept a request

    items = todo.objects.all() #ORM queries the database for all of the to-do entries.

    return render_to_response('index.html', {'items': items}) #Responds with passing the object items (contains info from the DB) to the template index.html

Now all that’s left is to create our template in the todo/core/templates/ directory. In this template, we want to iterate through all of the items (in the object items) and display them on the page. All of the Django logic is wrapped with curly braces; if it’s a variable, then it is wrapped with two curly braces.


{% for x in items %}
<p>{{ }} - {{ x.created|date:"D d M Y" }}</p>

<p>{{ x.description }}</p>
<hr />
{% endfor %}

You’re finished! Add a few to-do items in the admin panel, and then go to . Your layout should look similar to the image below.


作者:zihua | 分类: Django | 标签: django | 阅读: 988 | 发布于: 2014-01-20 23时 |