www.it-ebooks.info
Python Web Development
with Django®
www.it-ebooks.info
Developer’s Library
ESSENTIAL REFERENCES FOR PROGRAMMING PROFESSIONALS
Developer’s Library books are designed to provide practicing programmers with
unique, high-quality references and tutorials on the programming languages and
technologies they use in their daily work.
All books in the Developer’s Library are written by expert technology practitioners
who are especially skilled at organizing and presenting information in a way that’s
useful for other programmers.
Key titles include some of the best, most widely acclaimed books within their
topic areas:
PHP & MySQL Web Development
Python Essential Reference
Luke Welling & Laura Thomson
ISBN 978-0-672-32916-6
David Beazley
ISBN-13: 978-0-672-32862-6
MySQL
Programming in Objective-C
Paul DuBois
ISBN-13: 978-0-672-32938-8
Stephen G. Kochan
ISBN-13: 978-0-321-56615-7
Linux Kernel Development
PostgreSQL
Robert Love
ISBN-13: 978-0-672-32946-3
Korry Douglas
ISBN-13: 978-0-672-33015-5
Developer’s Library books are available at most retail and online bookstores, as well as
by subscription from Safari Books Online at safari.informit.com
Developer’s
Library
informit.com/devlibrary
www.it-ebooks.info
Python Web Development
with Django®
Jeff Forcier, Paul Bissex, Wesley Chun
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Cape Town • Sydney • Tokyo • Singapore • Mexico City
www.it-ebooks.info
Many of the designations used by manufacturers and sellers to distinguish their products
are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital
letters or in all capitals.
The authors and publisher have taken care in the preparation of this book, but make no
expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or
arising out of the use of the information or programs contained herein.
The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and
content particular to your business, training goals, marketing focus, and branding interests.
For more information, please contact:
U.S. Corporate and Government Sales
(800) 382-3419
[email protected]
For sales outside the United States, please contact:
Editor-In-Chief
Mark Taub
Acquisitions Editor
Debra Williams
Cauley
Development
Editor
Michael Thurston
Managing Editor
Kristy Hart
Project Editor and
Copy Editor
Jovana
San Nicolas-Shirley
Indexer
Cheryl Lenser
Proofreader
Geneil Breeze
International Sales
[email protected]
Publishing
Coordinator
Kim Boedigheimer
Visit us on the Web: informit.com/aw
Library of Congress Cataloging-in-Publication Data:
Forcier, Jeff, 1982Python web development with Django / Jeff Forcier, Paul Bissex, Wesley Chun.
p. cm.
Includes index.
ISBN-10: 0-13-235613-9 (pbk. : alk. paper)
ISBN-13: 978-0-13-235613-8 (pbk. : alk. paper) 1. Web site development. 2. Django
(Electronic resource) 3. Python (Computer program language) 4. Web sites—Authoring programs. I. Bissex, Paul. II. Chun, Wesley. III. Title.
TK5105.8885.D54F68 2009
006.7’6—dc22
2008037134
Copyright © 2009 Pearson Education, Inc.
All rights reserved. Printed in the United States of America. This publication is protected by
copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, write to:
Pearson Education, Inc
Rights and Contracts Department
501 Boylston Street, Suite 900
Boston, MA 02116
Fax (617) 671 3447
ISBN-13: 978-0-13-235613-8
ISBN-10: 0-13-235613-9
Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville,
Indiana.
First printing October 2008
www.it-ebooks.info
Cover Designer
Gary Adair
Compositor
Jake McFarland
❖
To Brian Levine, for introducing me to Python, a small
thing that has made a big difference.To my parents,
for allowing me to monopolize the family computer
while growing up. And to my wife, for her loving support
and understanding.
—Jeff Forcier
To my late father Henry, who taught me to tinker; to my
mother Glenda, who taught me to write; and to my wife
Kathleen, a brilliant star in my life.
—Paul Bissex
To my wonderful children, Leanna Xin-Yi and
Daylen Xin-Zhi, for whom I’ve had to develop multiple
pairs of eyes with which to keep watch over, and who
are miraculously able to temporarily transport me back
in time to remind me of what childhood and its
amazing wonders were like.
—Wesley Chun
❖
www.it-ebooks.info
Table of Contents
Introduction
1
Where Web Frameworks Come From
1
A Better Way
2
We’re Not in Kansas Anymore
2
Web Development Is Better with Python and Django
3
I: Getting Started
1 Practical Python for Django
Python Skills Are Django Skills
Getting Started: Python’s Interactive Interpreter
Python Basics
7
7
8
10
Comments
10
Variables and Assignment
10
Operators
11
Python Standard Types
11
Object Boolean Values
12
Numbers
12
Numeric Operators
13
Numeric Built-in and Factory Functions
14
Sequences and Iterables
14
Lists
17
Strings
19
Sequence Built-ins and Factory Functions
25
Mapping Type: Dictionaries
26
Standard Type Summary
28
Flow Control
28
Conditionals
29
Loops
29
Exception Handling
30
The finally Clause
31
Throwing Exceptions with raise
32
Files
33
Functions
34
www.it-ebooks.info
Declaring and Calling Functions
34
Functions Are First-Class Objects
36
Anonymous Functions
38
*args and **kwargs
40
Decorators
42
Object-Oriented Programming
44
Class Definitions
44
Instantiation
45
Subclassing
46
Inner Classes
46
Regular Expressions
47
The re module
47
Searching Versus Matching
48
Common Gotchas
48
Single-Item Tuples
48
Modules
48
Mutability
50
Constructor Versus Initializer
52
Coding Style (PEP 8 and Beyond)
53
Indent Four Spaces
53
Use Spaces and Not Tabs
53
Don’t Write Single-Line Suites
on the Same Line as the Header
54
Create Documentation Strings
(aka “docstrings”)
54
Summary
2 Django for the Impatient: Building a Blog
55
57
Creating the Project
58
Running the Development Server
59
Creating the Blog Application
61
Designing Your Model
62
Setting Up the Database
62
Using a Database Server
63
Using SQLite
63
Creating the Tables
Setting Up the Automatic admin Application
www.it-ebooks.info
64
65
Trying Out the admin
66
Making Your Blog’s Public Side
70
Creating a Template
70
Creating a View Function
71
Creating a URL Pattern
72
Finishing Touches
73
Template Niceties
73
Date-Based Ordering
74
Timestamp Formatting Via a Template Filter
75
Summary
75
3 Starting Out
77
Dynamic Web Site Basics
77
Communication: HTTP URLs, Requests,
,
Responses
78
Data Storage: SQL and Relational
Databases
78
Presentation: Rendering Templates into
HTML and Other Formats
79
Putting It All Together
79
Understanding Models, Views, and Templates
79
Separating the Layers (MVC)
79
Models
80
Views
81
Templates
81
Overall Django Architecture
82
Core Philosophies of Django
82
Django Tries to Be Pythonic
84
Don’t Repeat Yourself (DRY)
84
Loose Coupling and Flexibility
84
Rapid Development
85
Summary
86
II: Django in Depth
4 Defining and Using Models
Defining Models
89
89
Why Use an ORM?
89
www.it-ebooks.info
Django’s Rich Field Types
91
Relationships Between Models
93
Model Inheritance
97
Meta Inner Class
100
Admin Registration and Options
101
Using Models
102
Creating and Updating Your Database
Using manage.py
103
Query Syntax
104
Utilizing SQL Features Django Doesn’t
Provide
112
Summary
5 URLs, HTTP Mechanisms, and Views
URLs
Introduction to URLconfs
116
117
117
117
Replacing Tuples with url
119
Using Multiple patterns Objects
119
Including Other URL Files with include
120
Function Objects Versus Function-Name
Strings
121
Modeling HTTP: Requests, Responses,
and Middleware
122
Request Objects
123
Response Objects
125
Middleware
126
Views/Logic
127
Just Python Functions
128
Generic Views
128
Semi-generic Views
130
Custom Views
131
Summary
133
6 Templates and Form Processing
Templates
135
135
Understanding Contexts
135
Template Language Syntax
136
Forms
Defining Forms
www.it-ebooks.info
142
142
Filling Out Forms
147
Validation and Cleaning
149
Form Display
150
Widgets
152
Summary
154
III: Django Applications by Example
7 Photo Gallery
159
The Model
160
Preparing for File Uploads
161
Installing PIL
162
Testing ImageField
163
Building Our Custom File Field
164
Initialization
166
Adding Attributes to the Field
167
Saving and Deleting the Thumbnail
168
Using ThumbnailImageField
169
Setting Up DRY URLs
169
The Item App’s URL Layout
172
Tying It All Together with Templates
173
Summary
179
8 Content Management System
181
What’s a CMS?
181
The Un-CMS: Flatpages
182
Enabling the Flatpages App
182
Flatpage Templates
184
Testing It Out
184
Beyond Flatpages: A Simple Custom CMS
Making the Model
185
186
Imports
188
Completing the Model
188
Controlling Which Stories Are Viewed
189
Working with Markdown
190
URL Patterns in urls.py
192
Admin Views
193
Displaying Content Via Generic Views
196
www.it-ebooks.info
Template Layout
196
Displaying Stories
198
Adding Search
199
Managing Users
201
Supporting Workflow
202
Possible Enhancements
202
Summary
203
9 Liveblog
205
What Exactly Is Ajax?
205
Why Ajax Is Useful
206
Planning the Application
206
Choosing an Ajax Library
207
Laying Out the Application
208
Putting the Ajax In
211
The Basics
212
The “X” in Ajax (Or XML Versus JSON)
212
Installing the JavaScript Library
213
Setting Up and Testing jQuery
214
Creating the View Function
216
Using the View Function Via JavaScript
217
Summary
219
10 Pastebin
221
Defining the Model
222
Creating the Templates
223
Designing the URLs
225
Trying It Out
226
Limiting Number of Recent Pastes Displayed
229
Syntax Highlighting
230
Cleanup Via Cron Job
231
Summary
232
IV: Advanced Django Techniques and Features
11 Advanced Django Programming
Customizing the Admin
Changing Layout and Style Using Fieldsets
www.it-ebooks.info
235
235
236
Extending the Base Templates
237
Adding New Views
238
Authentication Decorators
239
Using Syndication
240
The Feed Class
240
Giving the Feed a URL
242
Doing More with Feeds
242
Generating Downloadable Files
243
Nagios Configuration Files
243
vCard
244
Comma-Separated Value (CSV)
245
Charts and Graphs Using PyCha
246
Enhancing Django’s ORM with Custom Managers
Changing the Default Set of Objects
Adding New Manager Methods
Extending the Template System
248
248
249
250
Simple Custom Template Tags
250
Inclusion Tags
253
Custom Filters
256
More Complex Custom Template Tags
258
Alternative Templating
258
Summary
260
12 Advanced Django Deployment
Writing Utility Scripts
261
261
Cronjobs for Cleanup
262
Data Import/Export
263
Customizing the Django Codebase Itself
264
Caching
265
A Basic Caching Recipe
265
Caching Strategies
267
Caching Backend Types
272
Testing Django Applications
274
Doctest Basics
275
Unittest Basics
276
Running Tests
276
Testing Models
276
Testing Your Entire Web App
278
www.it-ebooks.info
Testing the Django Codebase Itself
Summary
279
281
V: Appendices
A Command Line Basics
Putting the “Command” in “Command Line”
285
285
Options and Arguments
288
Pipes and Redirection
289
Environment Variables
291
The Path
293
Summary
294
B Installing and Running Django
Python
295
295
Mac OS X
296
Unix/Linux
296
Windows
296
Updating Your Path
296
Testing
299
Optional Add-ons
300
Django
Packaged Releases
301
302
Development Version
302
Installation
302
Testing
303
Web Server
The Built-In Server: Not for Production
303
303
The Standard Approach: Apache and
mod_python
304
The Flexible Alternative: WSGI
306
Another Approach: Flup and FastCGI
307
SQL Database
SQLite
308
308
PostgreSQL
309
MySQL
310
Oracle
311
Other Databases
311
Summary
www.it-ebooks.info
311
C Tools for Practical Django Development
Version Control
313
313
The Trunk and Branches
314
Merging
314
Centralized Version Control
315
Decentralized Version Control
315
Version Control for Your Project
316
Project Management Software
Trac
318
319
Text Editors
319
Emacs
319
Vim
320
TextMate
320
Eclipse
320
D Finding, Evaluating, and Using Django
Applications
321
Where to Look for Applications
321
How to Evaluate Applications
322
How to Use Applications
323
Sharing Your Own Application
323
E Django on the Google App Engine
325
Why the App Engine Matters
325
Pure Google App Engine Applications
326
Limitations of the App Engine Framework
326
Google App Engine Helper for Django
327
Getting the SDK and the Helper
327
More on the Helper
327
Integrating the App Engine
328
Copying the App Engine Code to Your Project
328
Integrating the App Engine Helper
329
Porting Your Application to App Engine
330
Taking a Test Drive
330
Adding Data
331
www.it-ebooks.info
Creating a New Django Application That Runs
on App Engine
333
Summary
334
Online Resources
334
F Getting Involved in the Django Project
337
Index
339
Colophon
375
www.it-ebooks.info
This page intentionally left blank
www.it-ebooks.info
Preface
Welcome to Django!
Greetings, and welcome to Django! We’re glad to have you along on our journey.You
will discover a powerful Web application framework that lets you do everything
rapidly—from designing and developing the original application to updating its features
and functionality without requiring major changes to the codebase.
About This Book
Several Django books are already on the market, but ours differs from most in that we
focus equally on three areas: Django basics, a variety of example applications, and
advanced Django topics. Our intent is to make this the most well-rounded book on the
subject, one you find useful regardless of background, and which will give you a complete picture of the framework and what you can do with it.
Chapter Guide
In Figure 0.1, you see recommended starting points for your reading depending on your
Python and Django experience. Of course, we recommend a cover-to-cover treatment,
but the diagram will help if time is not on your side. Regardless of your experience, you
are always welcome to look at the applications because reading and studying code is one
of the best ways to learn.We also provide this chapter-by-chapter reading guide to
further help direct you to where you need to read.
Part I, “Getting Started”
Part I covers the basic material needed to introduce users new to Django and/or
Python, although we recommend Chapter 3, “Starting Out,” even to advanced readers.
Chapter 1, “Practical Python for Django”
This chapter is an introduction for readers who are new to Python. In one comprehensive chapter, we show you not only the syntax, but also go a bit more in-depth and
expose you to Python’s memory model and data types, especially constructs commonly
used in Django.
www.it-ebooks.info
Know Python
but new
to Django
Brand New
to Django
and Python
Know Python
and some
Django already
Know Python
and Django
well but want
advanced
usage
Chp 7
Photo Gallery
Chp 8
CMS
Chp 1
Practical
Python
Chp 2
Impatient
(blog)
Chp 9
Liveblog
Chp 3
Starting
Out
Chp 10
Pastebin
Part I: Getting Started
Part III: Applications
Chp 4
Models
Chp 5
Views
Chp 6
Templates
Part II: Django in Depth
Chp 11
Advanced
Django
Programming
Chp 12
Advanced
Django
Deployment
Appendices
A-F
Part IV: Advanced
Figure 0.1
Suggested reading guide based on your Python and/or
Django experience
Chapter 2, “Django for the Impatient: Building a Blog”
This is a chapter for those who want to skip any Python introduction and want to dive
immediately into a Django application that can be completed in 15-20 minutes. It gives
a good overview of what’s possible with the framework.
Chapter 3, “Starting Out”
For those with a bit more patience, this chapter serves as an introduction to all the foundations of developing Web-based applications (useful both for newbies and experienced
www.it-ebooks.info
coders alike). Once the formalities are over, we describe how each concept fits into the
world of Django as well as what its philosophies are and how it may differ from other
Web application frameworks.
Part II, “Django in Depth”
Part II covers all the basic components of the framework, laying the foundation for the
example applications in Part III, “Django Applications by Example.”
Chapter 4, “Defining and Using Models”
In Chapter 4, learn how to define and work with your data model, including the basics
of Django’s object-relational mapper (ORM) from simple fields up to complex relations.
Chapter 5, “URLs, HTTP Mechanisms, and Views”
This chapter goes into detail on how Django handles URL processing and the rest of
the HTTP protocol, including middleware layers, as well as how to use Django’s timesaving generic views, and how to write custom or partially custom views from scratch.
Chapter 6, “Templates and Form Processing”
Chapter 6 covers the final major piece of the framework, where we explore Django’s
template language and its form-handling mechanisms. It covers how to display data to
your users and get data back from them.
Part III, “Django Applications by Example”
In Part III, we create four distinct applications, each highlighting a different aspect or
component of Django development, both to introduce new general ideas and to expand
on the concepts found in Parts I and II.
Chapter 7, “Photo Gallery”
In Chapter 7, learn how to apply the “Don’t Repeat Yourself ” convention to your URL
structure and create a new thumbnail-creating image form field, while you make a simple photo gallery application.
Chapter 8, “Content Management System”
Chapter 8 contains two related approaches to creating a CMS or CMS-like system and
covers the use of a number of “contrib” Django applications.
Chapter 9, “Liveblog”
Chapter 9 covers writing a “liveblog”—a site that makes use of advanced JavaScript
techniques, serves as a backdrop for applying AJAX to a Django project, and shows how
easy it is to use any AJAX toolkit you want.
Chapter 10, “Pastebin”
In Chapter 10, learn the power of Django’s generic views as we create a pastebin using
almost no custom logic whatsoever.
www.it-ebooks.info