Django at the Ann Arbor Software Development Study Group
I was supposed to lead a jam last December at the Ann Arbor Software Development Study Group, but a client project postponed it. On Tuesday, February 2, we’ll try one more time. The topic is “Zero to Django: Writing Web Apps with Python Using the Django Framework”. By the end of the session, you will be collecting form data and redisplaying it on a webpage.
NOTE: This exercise is meant to get you collecting data quickly and I’ll be skipping a lot of explanations. Feel free to ask questions or research any areas that you may find particularly tricky.
On with the jam!
Pre-Requisites:
Though there is only one requirement for this session - installing Django - you'll want to get this done ahead of time. It's not difficult, but there are a few steps and it will take enough time that it could keep you from completing all the exercises. To install Django, go to http://docs.djangoproject.com/en/dev/topics/install for a detailed description of what you need to do. Before following that link, here's a couple of suggestions:
- Be sure to install Python 2.5 (Python 2.6 will probably be fine). Django will not run with the 3.x series of Python.
- You can skip installing Apache and mod-wsgi. This session is only about how to use the framework which can be done completely within the development environment provided by Django.
- You can also skip the section on getting a database running. We'll be using SQLite which is baked into Python 2.5 and later versions.
- Be sure to install an official release of Django. Under "Installing an official release", click on "download page" in line item 1. Use the version under "Option 1: Get the latest official version".
The Exercise:
Create a folder where all of your Django apps can you live. I'm using Windows and I'm putting all of my Django projects in the C:\django directory.
- From the command line, navigate to the directory you just created
- from the command line, run "python django-admin.py startproject people". You may have to explicity give the path of the django-admin.py file which can be found in python25/Lib/site-packages/[django dir]. If you copied the file as suggested by the installation directions, just use that version of the file instead. Also, you may get a "permission denied" message. If that's the case, check your permissions on the folder.
- If you successfully completed step 3, you should now have a "people" directory. On my machine, the path is c:\django\people.
- Navigate to the directory mentioned in Step 4 and run "python manage.py runserver"
- Open up a browser and navigate to "http://localhost:8000/people". You should see a message congratulating you on "your first Django-powered Page"
Now that you’ve created a page, let’s configure our site so that we can do something useful.
- Django Projects contain one or more Apps (OK, they don’t have to contain Apps, but if you want to connect to a database they do). To create an app, run “python manage.py startapp dataentry”. The “manage.py” file can be found in the root of the people directory you created earlier. On my machine, the path is C:\django\people\manage.py.
- In the “settings.py” file contained within the project root, configure the database. For this exercise we’ll use SQLite since it comes bundled with Python 2.5 and all later versions:
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'peopledb'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
- In the settings file, you need to add your app to the INSTALLED_APPS section. Your INSTALLED_APPS section should look like the following (note the “people.dataentry” on the last line):
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
people.dataentry',
) -
Again in the settings file, add “"/templates",” to the TEMPLATE_DIRS setting.
Don’t worry about the extra lines. Those go beyond the scope of this session. If they really bother you, you can remove them. Just be aware that you’ll need add the extra comma (,) at the end so Python understands that this is a single item tuple.
Now that the configuration is done, it’s time to setup your database. To do that, we’ll need to open up model.py file inside your application directory. On my machine, that’s “c:\django\people\dataentry\model.py”. Your model should like the following:
from django.db import models
class Person(models.Model):
T_SHIRT_SIZE_CHOICES = (
("WS","Women's Small"),
("WM","Women's Medium"),
("WL","Women's Large"),
("S","Small"),
("M","Medium"),
("L","Large"),
("XL","X-Large"),
("2XL","2X-Large"),
("3XL","3X-Large"),
)
name = models.CharField(max_length=30)
t_shirt_size = models.CharField(max_length=10,
choices=T_SHIRT_SIZE_CHOICES)
special_dietary_concerns = models.BooleanField(
default=False)
special_dietary_concerns_comments = models.TextField(null=True,
blank=True)def __unicode__(self):
return "<Person %s %s %s>" % (
self.name,
self.t_shirt_size,
self.special_dietary_concerns)
Now that your model is in place, let’s make sure that it’s reflected in the database.
- From the command line in the directory where the model.py file lives (“c:\django\people\dataentry\model.py” on my machine), run “python manage.py syncdb”. A series of tables will be created.
- You will be prompted to create a superuser. Type “yes” and continue through the prompts.
That’s it! The Person class is now in the database. But how do you use it.? To test it out, run “python manage.py shell” from the command line. You’ll be placed into Python’s Interactive Console. Now run the following commands
- from dataentry.models import Person
- p = Person()
- p.name = “Me”
- p.t_shirt_size = “L”
- p.save()
- Person.objects.get(id=1)
That last command should have printed “<Person Me L False>” in the console. Assuming it did, how do we get this form on a webpage? Before we do that, let’s make a webpage first.
- Create a new folder called “templates” in the “c:\django\people\dataentry” directory.
- In the “c:\django\people\dataentry\templates” directory, create a new file called “template.html”
- In the template.html file, paste the following snippet “<h1>{{ hello }}</h1>” . Save the file.
You’ve just created a very basic template. To use it, make sure that your views.py file looks like the following:
from django.shortcuts import render_to_response
def hello(request):
hello = "Hello, World"
return render_to_response("template.html", locals())
Open “c:\django\people\urls.py” and make sure the following code is in it:
from django.conf.urls.defaults import *
from people.dataentry import viewsurlpatterns = patterns('',
(r'^hello/$', views.hello)
)
All the pieces should be in place for you to actually view your webpage. From the command line, run “python manage.py runserver”. Open your favorite web browser and navigate to http://localhost:8000/hello. You should be rewarded with “Hello, World” in a very large font. That’s all well and good, but what about that model we created? Let’s put it to good use right now. Let’s create a list.html in our template directory that looks something like the following:
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>T Shirt Size</th>
<th>Special Diet</th>
<th>Special Diet Comments</th>
</tr>
{% for person in people %}
<tr>
<td>{{ person.name }}</td>
<td>{{ person.t_shirt_size }}</td>
<td>{{ person.special_dietary_concerns }}</td>
<td>{{ person.special_dietary_concerns_comments }}</td>
</tr>
{% endfor %}
</body>
</html>
Now let’s create a new method in our view so that our views.py file looks like the following:
from django.shortcuts import render_to_response
from people.dataentry.models import Persondef hello(request):
hello = "Hello, World"
return render_to_response("template.html", locals())def list_people(request):
title = "List of People"
people = Person.objects.all()
return render_to_response("list.html", locals())
Switch to the urls.py file and wire a url to our new method. Our updated urls.py file should look like the following:
from django.conf.urls.defaults import *
from people.dataentry import viewsurlpatterns = patterns('',
(r'^hello/$', views.hello),
(r'^list/$', views.list_people),
)
From your web browser, navigate to http://localhost:8000/list. You should see the person you entered in the Interactive Console. Cool! By now you should see a pattern on how to create a new page in Django: create a template, create a new method in the view and then edit the urls.py file. Let’s add a bit more complexity by creating a form. Create a new forms.py file in the “C:\django\people\dataentry” directory. Put the following code block in that new file:
from django import forms
from models import Personclass PersonForm(forms.ModelForm):
class Meta(object):
model = Person
Create a new template in the template folder called “form.html” and put the following html inside it:
<html>
<head>
<title>Adding a Person</title>
</head>
<body>
<form method="post">
<table>
{{ form.as_table }}
</table>
<input type='submit'>
</form>
</body>
</html>
Switch over to your view.py file and modify it so that it looks like the following:
from django.shortcuts import render_to_response, HttpResponseRedirect
from people.dataentry.models import Person
from people.dataentry.forms import PersonFormdef hello(request):
hello = "Hello, World"
return render_to_response("template.html", locals())def list_people(request):
title = "List of People"
people = Person.objects.all()
return render_to_response("list.html", locals())def add_person(request):
title = "Add Person"
if 'name' in request.POST:
form = PersonForm(request.POST)
if form.errors:
errors = form.errors
else:
form.save()
return HttpResponseRedirect("../list")
else:
form = PersonForm()
return render_to_response("form.html", locals())
Now all you have to do is wire up the url in the urls.py file. Now when you successfully add a new person using the form you will be redirected back to the list of people where you will see your entry at the bottom of the list.





