1. Web Development With Django
A Basic Introduction
Nick Efford
nick.efford@gmail.com
pythoneering.blogspot.com
twitter.com/python33r
School of Computing
University of Leeds
YPy Workshop, 11 December 2010
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 1 / 31
2. Outline
1 Introduction
Setting Up
What Is Django?
2 Getting Started
Project Structure
Data Handling
The Admin Interface
3 Front-End Development
Views
Templates
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 2 / 31
3. Introduction Setting Up
Outline
1 Introduction
Setting Up
What Is Django?
2 Getting Started
Project Structure
Data Handling
The Admin Interface
3 Front-End Development
Views
Templates
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 3 / 31
4. Introduction Setting Up
Files Required
1 Create a directory for this tutorial
2 Copy django.py and django-example.zip from the
USB drive to the new directory
3 Unpack the two archives
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 4 / 31
5. Introduction Setting Up
Files Required
1 Create a directory for this tutorial
2 Copy django.py and django-example.zip from the
USB drive to the new directory
3 Unpack the two archives
Windows Users
Avoid spaces in pathnames!
Try unpacking Zip archives in C:tmppython or similar
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 4 / 31
6. Introduction Setting Up
Files Required
1 Create a directory for this tutorial
2 Copy django.py and django-example.zip from the
USB drive to the new directory
3 Unpack the two archives
Windows Users
Avoid spaces in pathnames!
Try unpacking Zip archives in C:tmppython or similar
Note
We assume you have Python 2.6 or 2.7 already installed . . .
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 4 / 31
7. Introduction Setting Up
Setting Up Django
Do one of the following:
• In django-trunk directory (the one containing README) do
python setup.py install
• Set PYTHONPATH to include django-trunk directory
Use Python interpreter to verify:
>>> import django
>>> django.VERSION
(1, 3, 0, 'alpha', 1)
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 5 / 31
8. Introduction What Is Django?
Outline
1 Introduction
Setting Up
What Is Django?
2 Getting Started
Project Structure
Data Handling
The Admin Interface
3 Front-End Development
Views
Templates
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 6 / 31
9. Introduction What Is Django?
What Is Django?
• High-level framework for rapid web development
• Complete stack of tools
• Data modelled with Python classes
• Production-ready data admin interface, generated dynamically
• Elegant system for mapping URLs to Python code
• ‘Generic views’ to handle common requests
• Clean, powerful template language
• Components for user authentication, form handling, caching . . .
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 7 / 31
10. Introduction What Is Django?
A Working Example
Football match results and league tables
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 8 / 31
11. Getting Started Project Structure
Outline
1 Introduction
Setting Up
What Is Django?
2 Getting Started
Project Structure
Data Handling
The Admin Interface
3 Front-End Development
Views
Templates
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 9 / 31
12. Getting Started Project Structure
Project Structure
Project
• A Python package on your PYTHONPATH
• Holds project-wide settings in settings.py
• Holds a URL configuration (URLconf) in urls.py
• Contains or references one or more apps
App
• A Python package on your PYTHONPATH
(typically created as a subpackage of the project itself)
• May contain data models in models.py
• May contain views in views.py
• May have its own URL configuration in urls.py
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 10 / 31
13. Getting Started Project Structure
Project Structure
Project
• A Python package on your PYTHONPATH
• Holds project-wide settings in settings.py
• Holds a URL configuration (URLconf) in urls.py
• Contains or references one or more apps
App
• A Python package on your PYTHONPATH
(typically created as a subpackage of the project itself)
• May contain data models in models.py
• May contain views in views.py
• May have its own URL configuration in urls.py
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 10 / 31
14. Getting Started Project Structure
Creating Projects & Apps
Creating a project:
django-admin.py startproject football
Creating an app within a project directory:
cd football
./manage.py startapp club
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 11 / 31
15. Getting Started Project Structure
Up & Running
1 Set PYTHONPATH to include parent of your project directory
2 Define new environment variable DJANGO_SETTINGS_MODULE,
setting it to project settings (football.settings)
3 Try running the development server:
./manage.py runserver
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 12 / 31
16. Getting Started Project Structure
settings.py
• Database used (PostgreSQL, MySQL, Oracle, SQLite . . . )
• Which apps & middleware components are active
• Paths to templates and static media
• How logging is done . . .
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 13 / 31
17. Getting Started Project Structure
settings.py
• Database used (PostgreSQL, MySQL, Oracle, SQLite . . . )
• Which apps & middleware components are active
• Paths to templates and static media
• How logging is done . . .
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME' : os.path.join(os.path.dirname(__file__), 'football.db'),
...
}
}
...
INSTALLED_APPS = (
...
'django.contrib.admin',
'football.club',
)
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 13 / 31
18. Getting Started Data Handling
Outline
1 Introduction
Setting Up
What Is Django?
2 Getting Started
Project Structure
Data Handling
The Admin Interface
3 Front-End Development
Views
Templates
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 14 / 31
19. Getting Started Data Handling
The Data Model
• A description of database layout, as a Python class
• Normally represents one database table
• Has fields that map onto columns of the table
• Many built-in field types
• CharField, TextField
• IntegerField, FloatField, DecimalField
• DateField, DateTimeField, TimeField
• EmailField, URLField
• ForeignKey . . .
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 15 / 31
20. Getting Started Data Handling
Example
from django.db import models
class Club(models.Model):
"""A football club."""
name = models.CharField(max_length=30)
year_established = models.PositiveSmallIntegerField()
ground = models.CharField(max_length=30)
class Meta:
ordering = ('name',)
def __unicode__(self):
return self.name
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 16 / 31
21. Getting Started Data Handling
Creating The Database
1 Optionally check table creation SQL:
./manage.py sql club
2 Sync installed apps with database:
./manage.py syncdb
3 Optionally check the outcome in the database:
./manage.py dbshell
4 Populate the database
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 17 / 31
22. Getting Started Data Handling
Creating & Saving Objects
Invoke constructor and call save method:
club = Club(name='Arsenal', year_established=1886,
ground='Emirates Stadium')
club.save()
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 18 / 31
23. Getting Started Data Handling
Creating & Saving Objects
Invoke constructor and call save method:
club = Club(name='Arsenal', year_established=1886,
ground='Emirates Stadium')
club.save()
. . . or call create method of Club model manager:
Club.objects.create(name='Arsenal', year_established=1886,
ground='Emirates Stadium')
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 18 / 31
24. Getting Started Data Handling
Retrieving Objects
Retrieve a single object with get:
club = Club.objects.get(name='Liverpool')
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 19 / 31
25. Getting Started Data Handling
Retrieving Objects
Retrieve a single object with get:
club = Club.objects.get(name='Liverpool')
Retrieve querysets with all, filter, etc:
for club in Club.objects.all():
print club
for club in Club.objects.filter(year_established=1878):
print club
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 19 / 31
26. Getting Started The Admin Interface
Outline
1 Introduction
Setting Up
What Is Django?
2 Getting Started
Project Structure
Data Handling
The Admin Interface
3 Front-End Development
Views
Templates
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 20 / 31
27. Getting Started The Admin Interface
Registering Models
In admin.py in the club app:
from django.contrib import admin
from football.club.models import Club
admin.site.register(Club)
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 21 / 31
28. Getting Started The Admin Interface
Registering Models
In admin.py in the club app:
from django.contrib import admin
from football.club.models import Club
admin.site.register(Club)
In top-level urls.py:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^clubs/', include('football.club.urls')),
...
)
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 21 / 31
29. Getting Started The Admin Interface
The Admin Interface
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 22 / 31
30. Front-End Development Views
Outline
1 Introduction
Setting Up
What Is Django?
2 Getting Started
Project Structure
Data Handling
The Admin Interface
3 Front-End Development
Views
Templates
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 23 / 31
31. Front-End Development Views
Generic Views
Provide ready-made logic for many common tasks:
• Issuing a redirect
• Displaying a paginated list of objects
• Displaying a ‘detail’ page for a single object
• Yearly, monthly or daily listing of date-based objects
• ‘Latest items’ page for date-based objects
• Object creation, updating, deletion (with/without authorisation)
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 24 / 31
32. Front-End Development Views
Generic Views Example
views.py
from django.views.generic import ListView
from football.club.models import Club
class ClubListView(ListView):
model = Club
context_object_name = 'clubs'
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 25 / 31
33. Front-End Development Views
Generic Views Example
views.py
from django.views.generic import ListView
from football.club.models import Club
class ClubListView(ListView):
model = Club
context_object_name = 'clubs'
urls.py
from django.conf.urls.defaults import *
from football.club.views import ClubListView
urlpatterns = patterns('',
(r'^$', ClubListView.as_view()),
...
)
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 25 / 31
34. Front-End Development Views
View Function
• Takes an HTTPRequest object as a parameter
• Returns an HTTPResponse object to caller
• Is associated with a particular URL via the URLconf
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 26 / 31
35. Front-End Development Views
View Function
• Takes an HTTPRequest object as a parameter
• Returns an HTTPResponse object to caller
• Is associated with a particular URL via the URLconf
from datetime import date
from django.http import HttpResponse
def today(request):
html = '<html><body><h2>%s</h2></body></html>' % date.today()
return HttpResponse(html)
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 26 / 31
36. Front-End Development Views
View Function
• Takes an HTTPRequest object as a parameter
• Returns an HTTPResponse object to caller
• Is associated with a particular URL via the URLconf
from datetime import date
from django.http import HttpResponse
def today(request):
html = '<html><body><h2>%s</h2></body></html>' % date.today()
return HttpResponse(html)
from django.shortcuts import render_to_response
from football.club.models import Club
def clubs(request):
data = { 'clubs': Club.objects.all() }
return render_to_response('clubs.html', data)
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 26 / 31
37. Front-End Development Templates
Outline
1 Introduction
Setting Up
What Is Django?
2 Getting Started
Project Structure
Data Handling
The Admin Interface
3 Front-End Development
Views
Templates
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 27 / 31
38. Front-End Development Templates
Templates
Text files containing
• Variables, replaced by values when the template is rendered
{{ today }}
• Filters that modify how values are displayed
{{ today|date:"D d M Y" }}
• Tags that control the logic of the rendering process
{% if name == "nick" %}
<p>Hello, Nick!</p>
{% else %}
<p>Who are you?</p>
{% endif %}
Django comes with a large collection of useful tags & filters, and you
can also define your own . . .
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 28 / 31
39. Front-End Development Templates
Template Example
settings.py
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 29 / 31
40. Front-End Development Templates
Template Example
settings.py
TEMPLATE_DIRS = (
os.path.join(os.path.dirname(__file__), 'templates'),
)
templates/club/club_list.html
{% extends "base.html" %}
{% block title %}Clubs{% endblock %}
{% block content %}
<h1>Clubs</h1>
<ol>
{% for club in clubs %}
<li>{{ club }}</li>
{% endfor %}
</ol>
{% endblock %}
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 29 / 31
41. Final Thoughts
Summary
We have shown you
• The structure of a Django project
• How models represent data in Django applications
• How data can be stored and queried via model instances
• How data can be managed through a dynamic admin interface
• How functionality is represent by views, each associated
with URLs that match a given pattern
• How views render a response using a template
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
42. Final Thoughts
Summary
We have shown you
• The structure of a Django project
• How models represent data in Django applications
• How data can be stored and queried via model instances
• How data can be managed through a dynamic admin interface
• How functionality is represent by views, each associated
with URLs that match a given pattern
• How views render a response using a template
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
43. Final Thoughts
Summary
We have shown you
• The structure of a Django project
• How models represent data in Django applications
• How data can be stored and queried via model instances
• How data can be managed through a dynamic admin interface
• How functionality is represent by views, each associated
with URLs that match a given pattern
• How views render a response using a template
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
44. Final Thoughts
Summary
We have shown you
• The structure of a Django project
• How models represent data in Django applications
• How data can be stored and queried via model instances
• How data can be managed through a dynamic admin interface
• How functionality is represent by views, each associated
with URLs that match a given pattern
• How views render a response using a template
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
45. Final Thoughts
Summary
We have shown you
• The structure of a Django project
• How models represent data in Django applications
• How data can be stored and queried via model instances
• How data can be managed through a dynamic admin interface
• How functionality is represent by views, each associated
with URLs that match a given pattern
• How views render a response using a template
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
46. Final Thoughts
Summary
We have shown you
• The structure of a Django project
• How models represent data in Django applications
• How data can be stored and queried via model instances
• How data can be managed through a dynamic admin interface
• How functionality is represent by views, each associated
with URLs that match a given pattern
• How views render a response using a template
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
47. Final Thoughts
Summary
We have shown you
• The structure of a Django project
• How models represent data in Django applications
• How data can be stored and queried via model instances
• How data can be managed through a dynamic admin interface
• How functionality is represent by views, each associated
with URLs that match a given pattern
• How views render a response using a template
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
48. Final Thoughts
Summary
We have shown you
• The structure of a Django project
• How models represent data in Django applications
• How data can be stored and queried via model instances
• How data can be managed through a dynamic admin interface
• How functionality is represent by views, each associated
with URLs that match a given pattern
• How views render a response using a template
Hopefully, you now have a sense of what it is like
to develop web applications in Django!
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 30 / 31
49. Final Thoughts
Finding Out More
• Project home
http://www.djangoproject.com/
• Sites built using Django
http://djangosites.org/
• Django developers
http://djangopeople.net/
• Django-based rapid development platform
http://pinaxproject.com/
• Apress books (http://www.apress.com/)
• The Definitive Guide to Django (2nd edition)
• Practical Django Projects (2nd edition)
• Pro Django
• Beginning Django E-Commerce
Nick Efford (Univ of Leeds) Web Development With Django YPy 2010-12-11 31 / 31