100% found this document useful (4 votes)
66 views

(FREE PDF Sample) Definitive Guide To Django Web Development Done Right Second Edition Adrian Holovaty Ebooks

ebook

Uploaded by

liinatvedlin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
66 views

(FREE PDF Sample) Definitive Guide To Django Web Development Done Right Second Edition Adrian Holovaty Ebooks

ebook

Uploaded by

liinatvedlin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

Full download ebook at ebookgate.

com

Definitive Guide to Django Web Development


Done Right Second Edition Adrian Holovaty

https://ebookgate.com/product/definitive-guide-to-
django-web-development-done-right-second-edition-
adrian-holovaty/

Download more ebook from https://ebookgate.com


More products digital (pdf, epub, mobi) instant
download maybe you interests ...

The Definitive Guide To Django Web Development Done


Right 2nd Edition Edition Apress

https://ebookgate.com/product/the-definitive-guide-to-django-web-
development-done-right-2nd-edition-edition-apress/

Web Development with Django Cookbook Bendoraitis

https://ebookgate.com/product/web-development-with-django-
cookbook-bendoraitis/

Node Web Development Second Edition David Herron

https://ebookgate.com/product/node-web-development-second-
edition-david-herron/

MODx Web Development Second Edition Antano Solar John

https://ebookgate.com/product/modx-web-development-second-
edition-antano-solar-john/
Web Development Recipes Second Edition Brian P. Hogan
Et Al.

https://ebookgate.com/product/web-development-recipes-second-
edition-brian-p-hogan-et-al/

ActionScript for Flash MX The Definitive Guide Second


Edition Colin Moock

https://ebookgate.com/product/actionscript-for-flash-mx-the-
definitive-guide-second-edition-colin-moock/

AppleScript The Definitive Guide Definitive Guides 1st


Edition Matt Neuburg

https://ebookgate.com/product/applescript-the-definitive-guide-
definitive-guides-1st-edition-matt-neuburg/

The Definitive Guide to HTML5 Video 1st Edition Silvia


Pfeiffer

https://ebookgate.com/product/the-definitive-guide-to-
html5-video-1st-edition-silvia-pfeiffer/

The Definitive Guide to the ARM Cortex M3 Joseph Yiu

https://ebookgate.com/product/the-definitive-guide-to-the-arm-
cortex-m3-joseph-yiu/
 CYAN  YELLOW
 MAGENTA BLACK
 PANTONE 123 C

Books for professionals by professionals ® The EXPERT’s VOIce ® in Web Development


Companion
eBook Available Updated for
The Definitive Guide to Django: Django 1.1

The Definitive
Web Development Done Right, Second Edition
Dear Reader,
The Definitive Guide to

Guide to
This book is about Django, a Web development framework that saves you time
and makes Web development a joy. Using Django, you can build and maintain
high-quality Web applications with minimal fuss.
At its best, Web development is an exciting, creative act; at its worst, it can be a
repetitive, frustrating nuisance. Django lets you focus on the fun stuff—the crux of
your Web application—while easing the pain of the repetitive bits. In doing so, it
provides high-level abstractions of common Web development patterns, shortcuts
for frequent programming tasks, and clear conventions for how to solve problems.

Django
At the same time, Django tries to stay out of your way, letting you work outside
the scope of the framework as needed.
The goal of this book is to make you a Django expert. The focus is twofold.
First, we explain, in depth, what Django does and how to build Web applications
with it. Second, we discuss higher-level concepts where appropriate, answering
the question, “How can I apply these tools effectively in my own projects?” By
reading this book, you’ll learn the skills needed to develop powerful Web sites
quickly with code that is clean and easy to maintain.
Since we wrote the first edition of this book there have been substantial
backward-incompatible changes to Django. This edition of the book is updated
to cover Django 1.1 and should serve you well for some time.
Web Development Done Right
Adrian Holovaty and Jacob Kaplan-Moss

Second Django is a framework that saves you


Edition time and makes Web development a joy
THE APRESS ROADMAP
Companion eBook Practical Django Updated for
Projects, Second Edition Django 1.1
Beginning Python Pro Django

See last page for details


The Definitive Guide to
Django, Second Edition Second Edition
on $10 eBook version

Kaplan-Moss
SOURCE CODE ONLINE
www.apress.com http://djangobook.com ISBN 978-1-4302-1936-1 Holovaty,
Adrian Holovaty
and Jacob Kaplan-Moss
54499

US $44.99

Shelve in Benevolent Dictators for Life, Django


Web Development

User level: 9 781430 219361


Beginner–Intermediate

this print for content only—size & color not accurate spine = 1.024" 536 page count
The Definitive Guide
to Django
Web Development Done Right,
Second Edition

Adrian Holovaty and Jacob Kaplan-Moss

19361fm.indd 1 6/16/09 3:15:00 PM


The Definitive Guide to Django: Web Development Done Right, Second Edition
Copyright © 2009 by Adrian Holovaty and Jacob Kaplan-Moss
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
ISBN 13: 978-1-4302-1936-1
ISBN (electronic): 978-1-4302-1937-8
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence
of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark
owner, with no intention of infringement of the trademark.
Java™ and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc., in the
US and other countries. Apress, Inc., is not affiliated with Sun Microsystems, Inc., and this book was writ-
ten without endorsement from Sun Microsystems, Inc.
Lead Editor: Duncan Parkes
Technical Reviewer: Sean Legassick
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Tony Campbell,
Gary Cornell, Jonathan Gennick, Michelle Lowman, Matthew Moodie, Jeffrey Pepper, Frank Pohlmann,
Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh
Project Managers: Grace Wong and James Markham
Copy Editors: Nancy Sixsmith and Candace English
Associate Production Director: Kari Brooks-Copony
Production Editor: Katie Stence
Compositor: Patrick Cunningham
Proofreader: April Eddy
Indexer: BIM Indexing & Proofreading Services
Artist: April Milne
Cover Designer: Kurt Krames
Manufacturing Director: Tom Debolski
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor,
New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail [email protected], or
visit http://www.springeronline.com.
For information on translations, please contact Apress directly at 2855 Telegraph Avenue, Suite 600,
Berkeley, CA 94705. Phone 510-549-5930, fax 510-549-5939, e-mail [email protected], or visit http://www.
apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our Special
Bulk Sales–eBook Licensing web page at http://www.apress.com/info/bulksales.
The information in this book is distributed on an “as is” basis, without warranty. Although every precau-
tion has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability
to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indi-
rectly by the information contained in this work.
The source code for this book is available to readers at http://www.apress.com.

19361fm.indd 2 6/16/09 3:15:00 PM


This book is dedicated to the Django community.

19361fm.indd 3 6/16/09 3:15:00 PM


Contents at a Glance

About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii


About the Technical Reviewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxix
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxi
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiii
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxv

PART 1 ■■■ Getting Started


Chapter 1 Introduction to Django. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Chapter 2 Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Chapter 3 Views and URLconfs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Chapter 4 Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Chapter 5 Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Chapter 6 The Django Admin Site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Chapter 7 Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

PART 2 ■■■ Advanced Usage


Chapter 8 Advanced Views and URLconfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Chapter 9 Advanced Templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Chapter 10 Advanced Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Chapter 11 Generic Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Chapter 12 Deploying Django . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

iv

19361fm.indd 4 6/16/09 3:15:00 PM


PART 3 ■■■ Other Django Features
Chapter 13 Generating Non-HTML Content. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Chapter 14 Sessions, Users, and Registration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Chapter 15 Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Chapter 16 django.contrib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
Chapter 17 Middleware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Chapter 18 Integrating with Legacy Databases and Applications. . . . . . . . . . . . 317
Chapter 19 Internationalization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Chapter 20 Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341

PART 4 ■■■ Appendixes


Appendix A Model Definition Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Appendix B Database API Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Appendix C Generic View Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
Appendix D Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Appendix E Built-in Template Tags and Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
Appendix F The django-admin Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
Appendix G Request and Response Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479

19361fm.indd 5 6/16/09 3:15:00 PM


19361fm.indd 6 6/16/09 3:15:00 PM
Contents

About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii


About the Technical Reviewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxix
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxi
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxiii
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxv

PART 1 ■■■ Getting Started


Chapter 1 Introduction to Django. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

What Is a Web Framework?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3


The MVC Design Pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Django's History. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
How to Read This Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Required Programming Knowledge . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Required Python Knowledge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Required Django Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Chapter 2 Getting Started. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Installing Python. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Python Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Installation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Installing Django . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Installing an Official Release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Installing the Trunk Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Testing the Django Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

vii

19361fm.indd 7 6/16/09 3:15:00 PM


viii ■CO NTENT S

Setting Up a Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Using Django with PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Using Django with SQLite 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Using Django with MySQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Using Django with Oracle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Using Django Without a Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Starting a Project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Running the Development Server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
What's Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Chapter 3 Views and URLconfs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Your First Django-Powered Page: Hello World. . . . . . . . . . . . . . . . . . . . . . . 21


Your First View. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Your First URLconf. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
A Quick Note About 404 Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
A Quick Note About the Site Root . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
How Django Processes a Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Your Second View: Dynamic Content. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
URLconfs and Loose Coupling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Your Third View: Dynamic URLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Django’s Pretty Error Pages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
What's Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

Chapter 4 Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

Template-System Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Using the Template System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Creating Template Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Rendering a Template. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Multiple Contexts, Same Template. . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Context Variable Lookup. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Playing with Context Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Basic Template Tags and Filters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Filters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Philosophies and Limitations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Using Templates in Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

19361fm.indd 8 6/16/09 3:15:00 PM


■C O N T E N T S ix

Template Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
render_to_response() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
The locals() Trick . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Subdirectories in get_template(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
The include Template Tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Template Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
What's Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

Chapter 5 Models. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

The “Dumb” Way to Do Database Queries in Views . . . . . . . . . . . . . . . . . . 71


The MTV (or MVC) Development Pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Configuring the Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Your First App. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Defining Models in Python. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Your First Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Installing the Model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Basic Data Access. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Adding Model String Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Inserting and Updating Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Selecting Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Filtering Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Retrieving Single Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Ordering Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Chaining Lookups. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Slicing Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Updating Multiple Objects in One Statement. . . . . . . . . . . . . . . . . . . . 92
Deleting Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
What's Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

Chapter 6 The Django Admin Site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

The django.contrib Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95


Activating the Admin Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Using the Admin Site. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Adding Your Models to the Admin Site. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
How the Admin Site Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Making Fields Optional. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Making Date and Numeric Fields Optional . . . . . . . . . . . . . . . . . . . . 104
Customizing Field Labels. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

19361fm.indd 9 6/16/09 3:15:00 PM


x ■CO NTENT S

Custom ModelAdmin Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106


Customizing Change Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Customizing Edit Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Users, Groups, and Permissions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
When and Why to Use the Admin Interface—And When Not To. . . . . . . 117
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

Chapter 7 Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

Getting Data from the Request Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119


Information About the URL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Other Information About the Request. . . . . . . . . . . . . . . . . . . . . . . . . 120
Information About Submitted Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
A Simple Form-Handling Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Improving Our Simple Form-Handling Example. . . . . . . . . . . . . . . . . . . . . 125
Simple Validation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Making a Contact Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Your First Form Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Tying Form Objects into Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Changing How Fields Are Rendered. . . . . . . . . . . . . . . . . . . . . . . . . . 137
Setting a Maximum Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Setting Initial Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Adding Custom Validation Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Specifying Labels. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Customizing Form Design. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

PART 2 ■■■ Advanced Usage


Chapter 8 Advanced Views and URLconfs . . . . . . . . . . . . . . . . . . . . . . . . . . . 145

URLconf Tricks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145


Streamlining Function Imports. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Using Multiple View Prefixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Special-Casing URLs in Debug Mode. . . . . . . . . . . . . . . . . . . . . . . . . 148
Using Named Groups. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Understanding the Matching/Grouping Algorithm . . . . . . . . . . . . . . 150
Passing Extra Options to View Functions. . . . . . . . . . . . . . . . . . . . . . 150
Using Default View Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155

19361fm.indd 10 6/16/09 3:15:01 PM


■C O N T E N T S xi

Special-Casing Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156


Capturing Text in URLs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Determining What the URLconf Searches Against. . . . . . . . . . . . . . 158
Higher-Level Abstractions of View Functions . . . . . . . . . . . . . . . . . . 158
Wrapping View Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Including Other URLconfs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
How Captured Parameters Work with include() . . . . . . . . . . . . . . . . 163
How Extra URLconf Options Work with include() . . . . . . . . . . . . . . . 164
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

Chapter 9 Advanced Templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

Template Language Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167


RequestContext and Context Processors. . . . . . . . . . . . . . . . . . . . . . . . . . . 168
django.core.context_processors.auth . . . . . . . . . . . . . . . . . . . . . . . . 171
django.core.context_processors.debug. . . . . . . . . . . . . . . . . . . . . . . 171
django.core.context_processors.i18n . . . . . . . . . . . . . . . . . . . . . . . . 172
django.core.context_processors.request. . . . . . . . . . . . . . . . . . . . . . 172
Guidelines for Writing Your Own Context Processors . . . . . . . . . . . 172
Automatic HTML Escaping. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
How to Turn It Off. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Automatic Escaping of String Literals in Filter Arguments. . . . . . . 176
Inside Template Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Extending the Template System. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Creating a Template Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Writing Custom Template Filters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
Writing Custom Template Tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Writing the Compilation Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Writing the Template Node. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Registering the Tag. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Setting a Variable in the Context. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
Parsing Until Another Template Tag. . . . . . . . . . . . . . . . . . . . . . . . . . 184
Parsing Until Another Template Tag and Saving Contents. . . . . . . 185
Shortcut for Simple Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Inclusion Tags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Writing Custom Template Loaders. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Configuring the Template System in Standalone Mode . . . . . . . . . . . . . . 189
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190

19361fm.indd 11 6/16/09 3:15:01 PM


xii ■CO NTENT S

Chapter 10 Advanced Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

Related Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191


Accessing Foreign Key Values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
Accessing Many-to-Many Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Making Changes to a Database Schema. . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Adding Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Removing Fields. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Removing Many-to-Many Fields. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Removing Models. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Adding Extra Manager Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Modifying Initial Manager QuerySets . . . . . . . . . . . . . . . . . . . . . . . . . 198
Model Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Executing Raw SQL Queries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201

Chapter 11 Generic Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

Using Generic Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204


Generic Views of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Extending Generic Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
Making “Friendly” Template Contexts. . . . . . . . . . . . . . . . . . . . . . . . 207
Adding Extra Context. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
Viewing Subsets of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Complex Filtering with Wrapper Functions . . . . . . . . . . . . . . . . . . . . 210
Performing Extra Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212

Chapter 12 Deploying Django . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

Preparing Your Codebase for Production. . . . . . . . . . . . . . . . . . . . . . . . . . . 213


Turning Off Debug Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Turning Off Template Debug Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Implementing a 404 Template. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Implementing a 500 Template. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Setting Up Error Alerts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Setting Up Broken Link Alerts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Using Different Settings for Production. . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
DJANGO_SETTINGS_MODULE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217

19361fm.indd 12 6/16/09 3:15:01 PM


■C O N T E N T S xiii

Using Django with Apache and mod_python . . . . . . . . . . . . . . . . . . . . . . . 218


Basic Configuration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Running Multiple Django Installations on
the Same Apache Instance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Running a Development Server with mod_python. . . . . . . . . . . . . . 220
Serving Django and Media Files from
the Same Apache Instance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Error Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Handling a Segmentation Fault. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
An Alternative: mod_wsgi. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
Using Django with FastCGI. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
FastCGI Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
Running Your FastCGI Server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Using Django with Apache and FastCGI. . . . . . . . . . . . . . . . . . . . . . . 224
FastCGI and lighttpd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Running Django on a Shared-Hosting Provider with Apache. . . . . 227
Scaling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Running on a Single Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Separating Out the Database Server . . . . . . . . . . . . . . . . . . . . . . . . . 229
Running a Separate Media Server. . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Implementing Load Balancing and Redundancy . . . . . . . . . . . . . . . 230
Going Big. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Performance Tuning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
There’s No Such Thing As Too Much RAM . . . . . . . . . . . . . . . . . . . . 233
Turn Off Keep-Alive. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Use Memcached. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Use Memcached Often . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Join the Conversation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234

PART 3 ■■■ Other Django Features


Chapter 13 Generating Non-HTML Content. . . . . . . . . . . . . . . . . . . . . . . . . . . . 237

The Basics: Views and MIME Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237


Producing CSV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Generating PDFs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Installing ReportLab. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Writing Your View. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Complex PDFs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

19361fm.indd 13 6/16/09 3:15:01 PM


xiv ■CO NTENT S

Other Possibilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242


The Syndication-Feed Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
Initialization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
A Simple Feed. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
A More Complex Feed. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Specifying the Type of Feed. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
Enclosures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
Language. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
URLs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
Publishing Atom and RSS Feeds in Tandem. . . . . . . . . . . . . . . . . . . 248
The Sitemap Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Installation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Initialization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
Sitemap Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
Shortcuts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Creating a Sitemap Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
Pinging Google. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
What's Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254

Chapter 14 Sessions, Users, and Registration . . . . . . . . . . . . . . . . . . . . . . . . 255

Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Getting and Setting Cookies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
The Mixed Blessing of Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Django’s Session Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Enabling Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Using Sessions in Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Setting Test Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Using Sessions Outside of Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
When Sessions Are Saved . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Browser-Length Sessions vs. Persistent Sessions. . . . . . . . . . . . . . 262
Other Session Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
Users and Authentication. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
Enabling Authentication Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
Using Users. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
Logging In and Out. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
Limiting Access to Logged-in Users. . . . . . . . . . . . . . . . . . . . . . . . . . 269
Limiting Access to Users Who Pass a Test . . . . . . . . . . . . . . . . . . . . 269
Managing Users, Permissions, and Groups. . . . . . . . . . . . . . . . . . . . 271
Using Authentication Data in Templates . . . . . . . . . . . . . . . . . . . . . . 273

19361fm.indd 14 6/16/09 3:15:01 PM


■C O N T E N T S xv

Permissions, Groups, and Messages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274


Permissions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
Groups. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276

Chapter 15 Caching. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277

Setting Up the Cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278


Memcached . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
Database Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Filesystem Caching. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Local-Memory Caching. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Dummy Caching (for Development) . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Using a Custom Cache Back-End. . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
CACHE_BACKEND Arguments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
The Per-Site Cache. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
The Per-View Cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
Specifying Per-View Cache in the URLconf. . . . . . . . . . . . . . . . . . . . 283
Template Fragment Caching. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
The Low-Level Cache API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
Upstream Caches. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
Using Vary Headers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Controlling Cache: Using Other Headers. . . . . . . . . . . . . . . . . . . . . . . . . . . 288
Other Optimizations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
Order of MIDDLEWARE_CLASSES. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290

Chapter 16 django.contrib. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291

The Django Standard Library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291


Sites. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Scenario 1: Reusing Data on Multiple Sites . . . . . . . . . . . . . . . . . . . 293
Scenario 2: Storing Your Site Name/Domain in One Place. . . . . . . 293
How to Use the Sites Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
The Sites Framework’s Capabilities. . . . . . . . . . . . . . . . . . . . . . . . . . 294
CurrentSiteManager. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
How Django Uses the Sites Framework. . . . . . . . . . . . . . . . . . . . . . . 298
Flatpages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
Using Flatpages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
Adding, Changing, and Deleting Flatpages. . . . . . . . . . . . . . . . . . . . 301
Using Flatpage Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301

19361fm.indd 15 6/16/09 3:15:01 PM


xvi ■CO NTENT S

Redirects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Using the Redirects Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Adding, Changing, and Deleting Redirects . . . . . . . . . . . . . . . . . . . . 303
CSRF Protection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
A Simple CSRF Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
A More Complex CSRF Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Preventing CSRF. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Humanizing Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
apnumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
intcomma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
intword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
ordinal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Markup Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307

Chapter 17 Middleware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309

What’s Middleware?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309


Middleware Installation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Middleware Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Initializer: __init__(self) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Request Preprocessor: process_request(self, request). . . . . . . . . . 311
View Preprocessor: process_view(self, request, view,
args, kwargs). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Response Postprocessor: process_response(self,
request, response) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Exception Postprocessor: process_exception(self,
request, exception). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Built-in Middleware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Authentication Support Middleware. . . . . . . . . . . . . . . . . . . . . . . . . . 313
“Common” Middleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Compression Middleware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Conditional GET Middleware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Reverse Proxy Support (X-Forwarded-For Middleware) . . . . . . . . . 314
Session Support Middleware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
Sitewide Cache Middleware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
Transaction Middleware. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315

19361fm.indd 16 6/16/09 3:15:01 PM


■C O N T E N T S xvii

Chapter 18 Integrating with Legacy Databases and Applications. . . 317

Integrating with a Legacy Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317


Using inspectdb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Cleaning Up Generated Models. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
Integrating with an Authentication System. . . . . . . . . . . . . . . . . . . . . . . . . 319
Specifying Authentication Back-Ends. . . . . . . . . . . . . . . . . . . . . . . . . 319
Writing an Authentication Back-End. . . . . . . . . . . . . . . . . . . . . . . . . . 319
Integrating with Legacy Web Applications . . . . . . . . . . . . . . . . . . . . . . . . . 321
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322

Chapter 19 Internationalization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323

How to Specify Translation Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324


In Python Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
In Template Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
Working with Lazy Translation Objects . . . . . . . . . . . . . . . . . . . . . . . 329
How to Create Language Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Message Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Compiling Message Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
How Django Discovers Language Preference. . . . . . . . . . . . . . . . . . . . . . . 333
Using Translations in Your Own Projects. . . . . . . . . . . . . . . . . . . . . . . . . . . 335
The set_language Redirect View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Translations and JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
The javascript_catalog View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
Using the JavaScript Translation Catalog . . . . . . . . . . . . . . . . . . . . . 337
Creating JavaScript Translation Catalogs . . . . . . . . . . . . . . . . . . . . . 339
Notes for Users Familiar with gettext. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
gettext on Windows. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340

Chapter 20 Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341

The Theme of Web Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341


SQL Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
The Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
Cross-Site Scripting (XSS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
The Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
Cross-Site Request Forgery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
Session Forging/Hijacking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
The Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346

19361fm.indd 17 6/16/09 3:15:01 PM


xviii ■CO NTENT S

E-mail Header Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347


The Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
Directory Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
The Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
Exposed Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
The Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
A Final Word on Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349

PART 4 ■■■ Appendixes


Appendix A Model Definition Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353

Fields. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
AutoField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
BooleanField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
CharField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
CommaSeparatedIntegerField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
DateField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
DateTimeField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
DecimalField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
EmailField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
FileField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
FilePathField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
FloatField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
ImageField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
IntegerField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
IPAddressField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
NullBooleanField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
PositiveIntegerField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
PositiveSmallIntegerField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
SlugField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
SmallIntegerField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
TextField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
TimeField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
URLField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
XMLField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

19361fm.indd 18 6/16/09 3:15:01 PM


■C O N T E N T S xix

Universal Field Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359


null . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
blank. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
choices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
db_column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
db_index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
db_tablespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
default . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
editable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
help_text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
primary_key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
unique . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
unique_for_date. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
unique_for_month. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
unique_for_year. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
verbose_name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
ForeignKey . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
ManyToManyField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
OneToOneField. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
Model Metadata Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
abstract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
db_table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
db_tablespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
get_latest_by . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
managed. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
ordering. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
proxy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
unique_together. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
verbose_name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
verbose_name_plural. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368

Appendix B Database API Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369

Creating Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370


What Happens When You Save?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Autoincrementing Primary Keys . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Saving Changes to Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Retrieving Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
Caching and QuerySets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373

19361fm.indd 19 6/16/09 3:15:01 PM


xx ■CO NTENT S

Filtering Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373


Chaining Filters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
Limiting QuerySets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
Query Methods That Return New QuerySets. . . . . . . . . . . . . . . . . . . 376
QuerySet Methods That Do Not Return QuerySets. . . . . . . . . . . . . . 379
Field Lookups. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
exact. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
iexact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
contains. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
icontains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
gt, gte, lt, and lte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
startswith. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
istartswith. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
endswith and iendswith . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
year, month, and day . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
isnull. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
The pk Lookup Shortcut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
Complex Lookups with Q Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
Related Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Lookups That Span Relationships. . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Foreign-Key Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
“Reverse” Foreign-Key Relationships . . . . . . . . . . . . . . . . . . . . . . . . 388
Many-to-Many Relationships. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
Queries over Related Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
Deleting Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
Shortcuts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
get_object_or_404() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
get_list_or_404(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
Falling Back to Raw SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393

Appendix C Generic View Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395

Common Arguments to Generic Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395


“Simple” Generic Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
Rendering a Template. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
Redirecting to Another URL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397

19361fm.indd 20 6/16/09 3:15:02 PM


■C O N T E N T S xxi

List/Detail Generic Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397


Lists of Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
Detail Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
Date-Based Generic Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
Archive Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
Year Archives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
Month Archives. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
Week Archives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
Day Archives. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
Archive for Today. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Date-Based Detail Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409

Appendix D Settings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413

The Basics of Settings Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413


Default Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Seeing Which Settings You’ve Changed . . . . . . . . . . . . . . . . . . . . . . 414
Using Settings in Python Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
Altering Settings at Runtime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
Creating Your Own Settings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Designating the Settings: DJANGO_SETTINGS_MODULE. . . . . . . . . . . . . 415
The django-admin.py Utility. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
On the Server (mod_python) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
Using Settings Without Setting DJANGO_SETTINGS_MODULE. . . . . . . . 416
Custom Default Settings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
Either configure() or DJANGO_SETTINGS_MODULE Is Required. . 417
Available Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
ABSOLUTE_URL_OVERRIDES. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
ADMIN_MEDIA_PREFIX. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
ADMINS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
ALLOWED_INCLUDE_ROOTS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
APPEND_SLASH. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
CACHE_BACKEND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
CACHE_MIDDLEWARE_KEY_PREFIX. . . . . . . . . . . . . . . . . . . . . . . . . . 418
DATABASE_ENGINE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
DATABASE_HOST. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
DATABASE_NAME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
DATABASE_OPTIONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
DATABASE_PASSWORD. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
DATABASE_PORT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419

19361fm.indd 21 6/16/09 3:15:02 PM


xxii ■CO NTENT S

DATABASE_USER. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
DATE_FORMAT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
DATETIME_FORMAT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
DEBUG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
DEFAULT_CHARSET. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
DEFAULT_CONTENT_TYPE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
DEFAULT_FROM_EMAIL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
DISALLOWED_USER_AGENTS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
EMAIL_HOST. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
EMAIL_HOST_PASSWORD. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
EMAIL_HOST_USER. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
EMAIL_PORT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
EMAIL_SUBJECT_PREFIX. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
FIXTURE_DIRS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
IGNORABLE_404_ENDS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
IGNORABLE_404_STARTS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
INSTALLED_APPS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
LANGUAGE_CODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
LANGUAGES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
MANAGERS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
MEDIA_ROOT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
MEDIA_URL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
MIDDLEWARE_CLASSES. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
MONTH_DAY_FORMAT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
PREPEND_WWW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
ROOT_URLCONF. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
SECRET_KEY. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
SEND_BROKEN_LINK_EMAILS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
SERIALIZATION_MODULES. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
SERVER_EMAIL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
SESSION_COOKIE_AGE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
SESSION_COOKIE_DOMAIN. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
SESSION_COOKIE_NAME. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
SESSION_COOKIE_SECURE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
SESSION_EXPIRE_AT_BROWSER_CLOSE. . . . . . . . . . . . . . . . . . . . . 425
SESSION_SAVE_EVERY_REQUEST. . . . . . . . . . . . . . . . . . . . . . . . . . . 425
SITE_ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
TEMPLATE_CONTEXT_PROCESSORS. . . . . . . . . . . . . . . . . . . . . . . . . 425
TEMPLATE_DEBUG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
TEMPLATE_DIRS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
TEMPLATE_LOADERS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426

19361fm.indd 22 6/16/09 3:15:02 PM


■C O N T E N T S xxiii

TEMPLATE_STRING_IF_INVALID. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
TEST_DATABASE_NAME . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
TEST_RUNNER. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
TIME_FORMAT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
TIME_ZONE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
URL_VALIDATOR_USER_AGENT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
USE_ETAGS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
USE_I18N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
YEAR_MONTH_FORMAT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428

Appendix E Built-in Template Tags and Filters. . . . . . . . . . . . . . . . . . . . . . . . 429

Built-in Tag Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429


autoescape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
block. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
comment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
cycle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
debug. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
extends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
firstof . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
ifchanged. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
ifequal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
ifnotequal. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
include. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
load. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
now. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
regroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
spaceless. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
ssi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
templatetag. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
url . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
widthratio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
with. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
Built-in Filter Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
add. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
addslashes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
capfirst. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
center. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442

19361fm.indd 23 6/16/09 3:15:02 PM


xxiv ■CO NTENT S

cut. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
default . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
default_if_none . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
dictsort. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
dictsortreversed. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
divisibleby. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
escape. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
escapejs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
filesizeformat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
first. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
fix_ampersands. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
floatformat. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
force_escape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
get_digit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
iriencode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
last . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
length. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
length_is . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
linebreaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
linenumbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
ljust. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
lower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
make_list. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
phone2numeric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
pluralize. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
pprint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
random. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
removetags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
rjust . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
safe. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
safeseq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
slice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
slugify. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
stringformat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
striptags. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
timesince. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
timeuntil. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
title. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451

19361fm.indd 24 6/16/09 3:15:02 PM


■C O N T E N T S xxv

truncatewords. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
truncatewords_html . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
unordered_list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
upper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
urlencode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
urlize. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
urlizetrunc. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
wordcount. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
wordwrap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
yesno . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453

Appendix F The django-admin Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455

Usage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
Getting Runtime Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
App Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
Determining the Version. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
Displaying Debug Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
Available Subcommands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
cleanup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
compilemessages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
createcachetable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
createsuperuser. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
dbshell. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
diffsettings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
dumpdata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
flush. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
inspectdb. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
loaddata <fixture fixture ...> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
makemessages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
reset <appname appname ...>. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
runfcgi [options]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
runserver. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
sql <appname appname ...>. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
sqlall <appname appname ...>. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
sqlclear <appname appname ...> . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
sqlcustom <appname appname ...> . . . . . . . . . . . . . . . . . . . . . . . . . 464
sqlflush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
sqlindexes <appname appname ...>. . . . . . . . . . . . . . . . . . . . . . . . . 464
sqlreset <appname appname ...> . . . . . . . . . . . . . . . . . . . . . . . . . . . 464

19361fm.indd 25 6/16/09 3:15:02 PM


xxvi ■CO NTENT S

sqlsequencereset <appname appname ...>. . . . . . . . . . . . . . . . . . . 464


startapp <appname> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
startproject <projectname>. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
syncdb. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
testserver <fixture fixture ...>. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
validate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
Default Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
--pythonpath. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
--settings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
--traceback. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
--verbosity. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
Extra Niceties. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
Syntax Coloring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
Bash Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467

Appendix G Request and Response Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 469

HttpRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
QueryDict Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
A Complete Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
HttpResponse. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
Construction HttpResponses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
Setting Headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
HttpResponse Subclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
Returning Errors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
Customizing the 404 (Not Found) View . . . . . . . . . . . . . . . . . . . . . . . 476
Customizing the 500 (Server Error) View. . . . . . . . . . . . . . . . . . . . . . 477

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479

19361fm.indd 26 6/16/09 3:15:02 PM


About the Authors

■Adrian Holovaty is a cocreator and co–Benevolent Dictator for Life of Django. He runs a Web
start-up called EveryBlock. He lives with his wife in Chicago and spends his free time attempt-
ing to play guitar in the style of Django Reinhardt.

■Jacob Kaplan-Moss is a lead developer and co–Benevolent Dictator for Life of Django. Jacob
is a partner at Revolution Systems, a consultancy that helps companies make the most of open
source software. Jacob previously worked for the Lawrence Journal-World, the locally owned
newspaper in Lawrence, Kansas where Django was developed. At Journal-World Jacob was the
lead developer of Ellington, a commercial Web-publishing platform for media companies.

xxvii

19361fm.indd 27 6/16/09 3:15:02 PM


19361fm.indd 28 6/16/09 3:15:02 PM
About the Technical Reviewer

■Sean Legassick has been creating software for over 15 years. His work
designing the architecture of South African open source framework
Chisimba has contributed significantly to software-engineering capac-
ity-building in Africa and other areas of the developing world. He is a
cofounder of MobGeo, a start-up developing innovative location-aware
mobile marketing solutions. Away from the world of software, he writes
on politics and culture.

xxix

19361fm.indd 29 6/16/09 3:15:02 PM


19361fm.indd 30 6/16/09 3:15:02 PM
Acknowledgments

T hanks to the many people who contributed to our online first drafts, and thanks to the folks
at Apress for their great editing.

xxxi

19361fm.indd 31 6/16/09 3:15:02 PM


19361fm.indd 32 6/16/09 3:15:02 PM
Preface

W elcome to the second edition of The Definitive Guide to Django, informally known as The
Django Book! This book aims to teach you how to use the Django Web framework to develop
Web sites efficiently.
When Jacob Kaplan-Moss and I wrote the first edition of this book, Django was still in a
pre-1.0 stage. Once Django version 1.0 was released, with its several backward-incompatible
changes, the first edition inevitably became outdated and people began demanding an update.
I’m happy to report this edition covers Django 1.1 and should serve you well for some time.
My thanks go to the many contributors who posted comments, corrections, and rants to
http://djangobook.com/, the accompanying Web site for this book, where I posted chapter
drafts as I wrote them. You guys are great.

Adrian Holovaty
Cocreator and co–Benevolent Dictator for Life, Django

xxxiii

19361fm.indd 33 6/16/09 3:15:02 PM


19361fm.indd 34 6/16/09 3:15:02 PM
Introduction

I n the early days, Web developers wrote every page by hand. Updating a Web site meant edit-
ing HTML; a “redesign” involved redoing every single page, one at a time.
As Web sites grew and became more ambitious, it quickly became obvious that that
situation was tedious, time-consuming, and ultimately untenable. A group of enterprising
hackers at NCSA (the National Center for Supercomputing Applications, where Mosaic, the
first graphical Web browser, was developed) solved this problem by letting the Web server
spawn external programs that could generate HTML dynamically. They called this protocol
the Common Gateway Interface, or CGI, and it changed the Web forever.
It’s hard now to imagine what a revelation CGI must have been: instead of treating HTML
pages as simple files on disk, CGI allows you to think of your pages as resources generated
dynamically on demand. The development of CGI ushered in the first generation of dynamic
Web sites.
However, CGI has its problems: CGI scripts need to contain a lot of repetitive “boilerplate”
code, they make code reuse difficult, and they can be difficult for first-time developers to write
and understand.
PHP fixed many of these problems, and it took the world by storm—it’s now by far the
most popular tool used to create dynamic Web sites, and dozens of similar languages and
environments (ASP, JSP, etc.) have followed PHP’s design closely. PHP’s major innovation is its
ease of use: PHP code is simply embedded into plain HTML. The learning curve for someone
who already knows HTML is extremely shallow.
But PHP has its own problems; its very ease of use encourages sloppy, repetitive, ill-
conceived code. Worse, PHP does little to protect programmers from security vulnerabilities,
and thus many PHP developers found themselves learning about security only once it was
too late.
These and similar frustrations led directly to the development of the current crop of
“third- generation” Web-development frameworks. These frameworks—Django and Ruby
on Rails appear to be the most popular these days—recognize that the Web’s importance has
escalated of late.
With this new explosion of Web development comes yet another increase in ambition;
Web developers are expected to do more and more every day.
Django was invented to meet these new ambitions. Django lets you build deep, dynamic,
interesting sites in an extremely short time. Django is designed to let you focus on the fun,
interesting parts of your job while easing the pain of the repetitive bits. In doing so, it provides
high-level abstractions of common Web-development patterns, shortcuts for frequent pro-
gramming tasks, and clear conventions on how to solve problems. At the same time, Django
tries to stay out of your way, letting you work outside the scope of the framework as needed.

xxxv

19361fm.indd 35 6/16/09 3:15:03 PM


xxxvi ■INT ROD UC TION

We wrote this book because we firmly believe that Django makes Web development bet-
ter. It’s designed to quickly get you moving on your own Django projects, and then ultimately
teach you everything you need to know to successfully design, develop, and deploy a site that
you’ll be proud of.
We’re extremely interested in your feedback. The online version of this book—available
at http://djangobook.com/—will let you comment on any part of the book and discuss it with
other readers. We’ll do our best to read all the comments posted there, and to respond to as
many as possible. If you prefer e-mail, please drop us a line at [email protected]. Either
way, we’d love to hear from you!
We’re glad you’re here, and we hope you find Django as exciting, fun, and useful as we do.

19361fm.indd 36 6/16/09 3:15:03 PM


P a r t 1

Getting Started

19361ch01_CMP2.indd 1 5/14/09 4:11:53 PM


19361ch01_CMP2.indd 2 5/14/09 4:11:53 PM
Chapter 1

Introduction to Django

T his book is about Django, a Web-development framework that saves you time and makes
Web development a joy. Using Django, you can build and maintain high-quality Web applica-
tions with minimal fuss.
At its best, Web development is an exciting, creative act; at its worst, it can be a repeti-
tive, frustrating nuisance. Django lets you focus on the fun stuff—the crux of your Web
application—while easing the pain of the repetitive bits. In doing so, it provides high-level
abstractions of common Web development patterns, shortcuts for frequent programming
tasks, and clear conventions for how to solve problems. At the same time, Django tries to stay
out of your way, letting you work outside the scope of the framework as needed.
The goal of this book is to make you a Django expert. The focus is twofold. First, we
explain, in depth, what Django does and how to build Web applications with it. Second, we
discuss higher-level concepts where appropriate, answering the question “How can I apply
these tools effectively in my own projects?” By reading this book, you’ll learn the skills needed
to develop powerful Web sites quickly, with code that is clean and easy to maintain.

What Is a Web Framework?


Django is a prominent member of a new generation of Web frameworks—but what does that
term mean, precisely?
To answer that question, let’s consider the design of a Web application written in Python
without a framework. Throughout this book, we’ll take this approach of showing you basic
ways to get work done without shortcuts, in the hope that you’ll recognize why shortcuts are
so helpful. (It’s also valuable to know how to get things done without shortcuts because short-
cuts aren’t always available. And most importantly, knowing why things work the way they do
makes you a better Web developer.)
One of the simplest, most direct ways to build a Python Web app from scratch is to use
the Common Gateway Interface (CGI) standard, which was a popular technique circa 1998.
Here’s a high-level explanation of how it works: create a Python script that outputs HTML,
then save the script to a Web server with a .cgi extension and visit the page in your Web
browser. That’s it.

19361ch01_CMP2.indd 3 5/14/09 4:11:53 PM


4 Ch apt er 1 ■  INTRODU C T ION T O DJ A NG O

Here’s a sample Python CGI script that displays the ten most recently published books
from a database. Don’t worry about syntax details; just get a feel for the basic things it’s doing.

#!/usr/bin/env python

import MySQLdb

print "Content-Type: text/html\n"


print "<html><head><title>Books</title></head>"
print "<body>"
print "<h1>Books</h1>"
print "<ul>"

connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db')


cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10")

for row in cursor.fetchall():


print "<li>%s</li>" % row[0]

print "</ul>"
print "</body></html>"

connection.close()

First, to fulfill the requirements of CGI, this code prints a “Content-Type” line, followed
by a blank line. It prints some introductory HTML, connects to a database, and runs a query to
retrieve the names of the latest ten books. Looping over those books, it generates an HTML list
of the titles. Finally, it prints the closing HTML and closes the database connection.
With a one-off page like this one, the write-it-from-scratch approach isn’t necessarily bad.
For one thing, this code is simple to comprehend—even a novice developer can read these 16
lines of Python and understand everything it does, from start to finish. There’s nothing else
to learn, no other code to read. It’s also simple to deploy: just save this code in a file that ends
with .cgi, upload that file to a Web server, and visit that page with a browser.
Despite its simplicity, this approach has a number of problems and annoyances. Ask your-
self these questions:

• What happens when multiple parts of your application need to connect to the data-
base? Surely that database-connecting code shouldn’t need to be duplicated in each
individual CGI script. The pragmatic thing to do would be to refactor it into a shared
function.
• Should a developer really have to worry about printing the “Content-Type” line and
remembering to close the database connection? This sort of boilerplate reduces pro-
grammer productivity and introduces opportunities for mistakes. These setup- and
teardown-related tasks would best be handled by some common infrastructure.

19361ch01_CMP2.indd 4 5/14/09 4:11:53 PM


C h a p t e r 1 ■  I N TRO D U C T I O N T O D JA N G O 5

• What happens when this code is reused in multiple environments, each with a sepa-
rate database and password? At this point, some environment-specific configuration
becomes essential.
• What happens when a Web designer who has no experience coding Python wishes to
redesign the page? One wrong character could crash the entire application. Ideally,
the logic of the page—the retrieval of book titles from the database—would be sepa-
rate from the HTML display of the page so that a designer could edit the latter without
affecting the former.

These problems are precisely what a Web framework intends to solve. A Web framework
provides a programming infrastructure for your applications so that you can focus on writ-
ing clean, maintainable code without having to reinvent the wheel. In a nutshell, that’s what
Django does.

The MVC Design Pattern


Let’s dive in with a quick example that demonstrates the difference between the previous
approach and a Web framework’s approach. Here’s how you might write the previous
CGI code using Django. The first thing to note is that we split it over three Python files
(models.py, views.py, urls.py) and an HTML template (latest_books.html):

# models.py (the database tables)

from django.db import models

class Book(models.Model):
name = models.CharField(max_length=50)
pub_date = models.DateField()

# views.py (the business logic)

from django.shortcuts import render_to_response


from models import Book

def latest_books(request):
book_list = Book.objects.order_by('-pub_date')[:10]
return render_to_response('latest_books.html', {'book_list': book_list})

# urls.py (the URL configuration)

from django.conf.urls.defaults import *


import views

urlpatterns = patterns('',
(r'^latest/$', views.latest_books),
)

19361ch01_CMP2.indd 5 5/14/09 4:11:53 PM


6 Ch apt er 1 ■  INTRODU C T ION T O DJ A NG O

# latest_books.html (the template)

<html><head><title>Books</title></head>
<body>
<h1>Books</h1>
<ul>
{% for book in book_list %}
<li>{{ book.name }}</li>
{% endfor %}
</ul>
</body></html>

Again, don’t worry about the particulars of syntax; just get a feel for the overall design. The
main thing to note here is the separation of concerns:

• The models.py file contains a description of the database table, represented by a


Python class. This class is called a model. Using it, you can create, retrieve, update, and
delete records in your database using simple Python code rather than writing repetitive
SQL statements.
• The views.py file contains the business logic for the page. The latest_books() function
is called a view.
• The urls.py file specifies which view is called for a given URL pattern. In this case, the
URL /latest/ will be handled by the latest_books() function. In other words, if your
domain is example.com, any visit to the URL http://example.com/latest/ will call the
latest_books() function.
• The latest_books.html file is an HTML template that describes the design of the page.
It uses a template language with basic logic statements—for example, {% for book in
book_list %}.

Taken together, these pieces loosely follow a pattern called Model-View-Controller (MVC).
Simply put, MVC is way of developing software so that the code for defining and accessing
data (the model) is separate from request-routing logic (the controller), which in turn is sepa-
rate from the user interface (the view). (We’ll discuss MVC in more depth in Chapter 5.)
A key advantage of such an approach is that components are loosely coupled. Each distinct
piece of a Django-powered Web application has a single key purpose and can be changed
independently without affecting the other pieces. For example, a developer can change the
URL for a given part of the application without affecting the underlying implementation. A
designer can change a page’s HTML without having to touch the Python code that renders it.
A database administrator can rename a database table and specify the change in a single place
rather than having to search and replace through a dozen files.
In this book, each component of MVC gets its own chapter. Chapter 3 covers views,
Chapter 4 covers templates, and Chapter 5 covers models.

19361ch01_CMP2.indd 6 5/14/09 4:11:53 PM


C h a p t e r 1 ■  I N TRO D U C T I O N T O D JA N G O 7

Django's History
Before we dive into more code, we should take a moment to explain Django’s history. We
noted earlier that we’ll be showing you how to do things without shortcuts so that you more
fully understand the shortcuts. Similarly, it’s useful to understand why Django was created,
because knowledge of the history will put into context why Django works the way it does.
If you’ve been building Web applications for a while, you’re probably familiar with the
problems in the CGI example we presented earlier. The classic Web developer’s path goes
something like this:

1. Write a Web application from scratch.


2. Write another Web application from scratch.
3. Realize the application from step 1 shares much in common with the application from
step 2.
4. Refactor the code so that application 1 shares code with application 2.
5. Repeat steps 2–4 several times.
6. Realize you’ve invented a framework.

This is precisely how Django itself was created!


Django grew organically from real-world applications written by a Web-development
team in Lawrence, Kansas, USA. It was born in the fall of 2003, when the Web programmers
at the Lawrence Journal-World newspaper, Adrian Holovaty and Simon Willison, began using
Python to build applications.
The World Online team, responsible for the production and maintenance of several local
news sites, thrived in a development environment dictated by journalism deadlines. For the
sites—including LJWorld.com, Lawrence.com, and KUsports.com—journalists (and manage-
ment) demanded that features be added and entire applications be built on an intensely fast
schedule, often with only days’ or hours’ notice. Thus, Simon and Adrian developed a time-
saving Web-development framework out of necessity—it was the only way they could build
maintainable applications under the extreme deadlines.
In summer 2005, after having developed this framework to a point where it was efficiently
powering most of World Online’s sites, the team, which now included Jacob Kaplan-Moss,
decided to release the framework as open source software. They released it in July 2005 and
named it Django, after the jazz guitarist Django Reinhardt.
Now, several years later, Django is a well-established open source project with tens of
thousands of users and contributors spread across the planet. Two of the original World
Online developers (the “Benevolent Dictators for Life,” Adrian and Jacob) still provide central
guidance for the framework’s growth, but it’s much more of a collaborative team effort.
This history is relevant because it helps explain two key things. The first is Django’s “sweet
spot.” Because Django was born in a news environment, it offers several features (such as its
admin site, covered in Chapter 6) that are particularly well suited for “content” sites—sites
like Amazon.com, Craigslist, and The Washington Post that offer dynamic, database-driven
information. Don’t let that turn you off, though—although Django is particularly good for
developing those sorts of sites, that doesn’t preclude it from being an effective tool for build-
ing any sort of dynamic Web site. (There’s a difference between being particularly effective at
something and being ineffective at other things.)

19361ch01_CMP2.indd 7 5/14/09 4:11:53 PM


8 Ch apt er 1 ■  INTRODU C T ION T O DJ A NG O

The second matter to note is how Django’s origins have shaped the culture of its open
source community. Because Django was extracted from real-world code rather than being an
academic exercise or a commercial product, it is acutely focused on solving Web-development
problems that Django’s developers themselves have faced—and continue to face. As a result,
Django itself is actively improved on an almost daily basis. The framework’s maintainers have
a vested interest in making sure Django saves developers time, produces applications that are
easy to maintain, and performs well under load. If nothing else, the developers are motivated
by their own selfish desires to save themselves time and enjoy their jobs. (To put it bluntly,
they eat their own dog food.)

How to Read This Book


In writing this book, we tried to strike a balance between readability and reference, with a bias
toward readability. Our goal with this book, as stated earlier, is to make you a Django expert,
and we believe the best way to teach is through prose and plenty of examples, rather than
providing an exhaustive but bland catalog of Django features. (As the saying goes, you can’t
expect to teach somebody how to speak a language merely by teaching them the alphabet.)
With that in mind, we recommend that you read Chapters 1 through 12 in order. They
form the foundation of how to use Django; once you’ve read them, you’ll be able to build
and deploy Django-powered Web sites. Specifically, Chapters 1 through 7 are the “core cur-
riculum,” Chapters 8 through 11 cover more-advanced Django usage, and Chapter 12 covers
deployment. The remaining chapters, 13 through 20, focus on specific Django features and
can be read in any order.
The appendixes are for reference. They, along with the free documentation at http://www.
djangoproject.com/, are probably what you’ll flip back to occasionally to recall syntax or find
quick synopses of what certain parts of Django do.

Required Programming Knowledge


Readers of this book should understand the basics of procedural and object-oriented pro-
gramming: control structures (e.g., if, while, for), data structures (lists, hashes/dictionaries),
variables, classes, and objects.
Experience in Web development is, as you may expect, very helpful, but it’s not required
to understand this book. Throughout the book, we try to promote best practices in Web devel-
opment for readers who lack this experience.

Required Python Knowledge


At its core, Django is simply a collection of libraries written in the Python programming
language. To develop a site using Django, you write Python code that uses these libraries.
Learning Django, then, is a matter of learning how to program in Python and understanding
how the Django libraries work.

19361ch01_CMP2.indd 8 5/14/09 4:11:53 PM


C h a p t e r 1 ■  I N TRO D U C T I O N T O D JA N G O 9

If you have experience programming in Python, you should have no trouble diving in. By
and large, the Django code doesn’t perform a lot of “magic” (i.e., programming trickery whose
implementation is difficult to explain or understand). For you, learning Django will be a mat-
ter of learning Django’s conventions and APIs.
If you don’t have experience programming in Python, you’re in for a treat. It’s easy to
learn and a joy to use! Although this book doesn’t include a full Python tutorial, it highlights
Python features and functionality where appropriate, particularly when code doesn’t immedi-
ately make sense. Still, we recommend you read the official Python tutorial, available online at
http://docs.python.org/tut/. We also recommend Mark Pilgrim’s free book Dive Into Python
(Apress, 2004), available at http://www.diveintopython.org/ and published in print by Apress.

Required Django Version


This book covers Django 1.1.
Django’s developers maintain backward compatibility within “major version” numbers.
This commitment means that, if you write an application for Django 1.1, it will still work for
1.2, 1.3, 1.9, and any other version number that starts with “1.” Once Django hits 2.0, though,
your applications might need to be rewritten—but version 2.0 is a long way away. As a point of
reference, it took more than three years to release version 1.0. (This is very similar to the com-
patibility policy that applies to the Python language itself: code that was written for Python 2.0
works with Python 2.6, but not necessarily with Python 3.0.) Given that this book covers Django
1.1, it should serve you well for some time.

Getting Help
One of the greatest benefits of Django is its kind and helpful user community. For help with
any aspect of Django—from installation to application design to database design to deploy-
ment—feel free to ask questions online.

• The Django users mailing list is where thousands of Django users hang out to ask and
answer questions. Sign up for free at http://www.djangoproject.com/r/django-users.
• The Django IRC channel is where Django users hang out to chat and help each other in
real time. Join the fun by logging on to #django on the Freenode IRC network.

What’s Next?
In the next chapter, we’ll get started with Django, covering installation and initial setup.

19361ch01_CMP2.indd 9 5/14/09 4:11:53 PM


19361ch01_CMP2.indd 10 5/14/09 4:11:53 PM
Chap ter 2

Getting Started

Installing Django is a multistep process because of the multiple moving parts in modern Web
development environments. In this chapter, we’ll walk you through how to install the frame-
work and its few dependencies.
Because Django is “just” Python code, it runs anywhere Python does—including on some
cell phones! But this chapter just covers the common scenarios for Django installations. We’ll
assume that you’re installing it either on a desktop/laptop machine or on a server.
Later on (in Chapter 12), we’ll cover how to deploy Django to a production site.

Installing Python
Django is written purely in Python, so the first step in installing the framework is to make sure
that you have Python installed.

Python Versions
The core Django framework works with any Python version from 2.3 to 2.6, inclusive. Django’s
optional Geographic Information Systems (GIS) support requires Python 2.4 to 2.6.
If you’re not sure which version of Python to install and you have complete freedom over
the decision, pick the latest one in the 2.x series: version 2.6. Although Django works equally
well with any version from 2.3 to 2.6, the later versions of Python have performance improve-
ments and additional language features you might like to use in your applications. Plus,
certain third-party Django add-ons that you might want to use might require a version newer
than Python 2.3, so using a later version of Python keeps your options open.

Django and Python 3.0

At the time of writing, Python 3.0 was released, but Django didn’t yet support it. Python 3.0 introduced a
substantial number of backward-incompatible changes to the language, so we expect that most major Python
libraries and frameworks, including Django, will take a few years to catch up.
If you’re new to Python and are wondering whether to learn Python 2.x or Python 3.x, our advice is to
stick with Python 2.x.

11

19361ch02_CMP2.indd 11 5/14/09 4:17:40 PM


12 Ch apt er 2 ■  G ETT ING S TARTE D

Installation
If you’re on Linux or Mac OS X, you probably have Python already installed. Type python at a
command prompt (or in Applications/Utilities/Terminal in OS X). If you see something like
this, Python is installed:

Python 2.4.1 (#2, Mar 31 2005, 00:05:10)


[GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Otherwise, you’ll need to download and install Python. It’s fast and easy, and detailed
instructions are available at http://www.python.org/download/.

Installing Django
At any given time, two distinct versions of Django are available to you: the latest official release
and the bleeding-edge trunk version. The version you decide to install depends on your priori-
ties. Do you want a stable and tested version of Django, or do you want a version containing
the latest features, perhaps so you can contribute to Django itself, at the expense of stability?
We recommend sticking with an official release, but it’s important to know that the trunk
development version exists because you’ll find it mentioned in the documentation and by
members of the community.

Installing an Official Release


Official releases have a version number, such as 1.0.3 or 1.1, and the latest one is always avail-
able at http://www.djangoproject.com/download/.
If you’re on a Linux distribution that includes a package of Django, it’s a good idea to use
the distributor’s version. That way, you’ll get security updates along with the rest of your sys-
tem packages.
If you don’t have access to a prepackaged version, you can download and install the
framework manually. To do so, first download the tarball, which will be named something
similar to Django-1.0.2-final.tar.gz. (It doesn’t matter which local directory you download
this file into; the installation process will put Django’s files in the right place.) Then unzip it
and run setup.py install, as you do with most Python libraries.
Here’s how that process looks on Unix systems:

1. tar xzvf Django-1.0.2-final.tar.gz


2. cd Django-*
3. sudo python setup.py install

On Windows, we recommend using 7-Zip (http://www.djangoproject.com/r/7zip/) to


unzip .tar.gz files. Once you’ve unzipped the file, start up a DOS shell (the command prompt)
with administrator privileges and run the following command from within the directory whose
name starts with Django-:

python setup.py install

19361ch02_CMP2.indd 12 5/14/09 4:17:40 PM


Another random document with
no related content on Scribd:
The Project Gutenberg eBook of The virtues of
common water
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

Title: The virtues of common water


or, The advantages thereof, in preventing and curing many
distempers : gathered from the writings of several eminent
physicians, and also from more than forty years experience

Author: John Smith

Contributor: Ralph Thoresby

Release date: April 14, 2024 [eBook #73394]

Language: English

Original publication: Dundee: T. Covill and Son, 1799

Credits: Charlene Taylor, Thiers Halliwell and the Online Distributed


Proofreading Team at https://www.pgdp.net (This file was
produced from images generously made available by The
Internet Archive/American Libraries.)
*** START OF THE PROJECT GUTENBERG EBOOK THE VIRTUES OF
COMMON WATER ***
Transcriber’s notes:
Apart from the corrections listed below, the text of this e-book has been preserved as in
the original.
universa → universal
Digeston → Digestion
liqours → liquors
hydochondriac → hypochondriac
childdren → children
loosenese → looseness
watet → water
appply → apply
rhey → they
absoltue → absolute
or → of
yest → yeast
distilation → distillation
mettalic → metallic
Leediensis → Leodiensis
sudirifics → sudorifics
primative → primitive
closs → close
it → is
decripedness → decrepidness
THE

VIRTUES
OF

COMMON WATER:
OR,

THE ADVANTAGES THEREOF,


IN

PR EVEN TIN G AND C URING MANY DISTEMP ER S.


GATHERED

From the writings of several eminent Physicians, and


also from more than forty years experience.

By JOHN SMITH, C. M.

To which is added,
SOME RULES FOR PRESERVING HEALTH BY DIET.

That’s the best physic, which doth cure our ills


Without the charge of ’pothecaries bills.

THE TENTH EDITION, WITH ADDITIONS.

COMMUNICATED BY
Mr RALPH THORESBY, F. R. S. and Others.

DUN DEE,
PRINTED BY T. COLVILL AND SON,
FOR

G . MIL L N, B OOKSEL L ER.


1799.
THE

VIRTUES
OF

COMMON WATER.

F
or the benefit of mankind in general, I have taken pains to give
the world an account of what I have found written in the works
of the most eminent physicians, concerning the good that mankind
may receive from the use of Common Water; and of the
informations I have had concerning the benefits thereof from others
by word of mouth; and of what I have discovered by my own
experience, from frequent trials, during a time that hath intervened
from that of thirty to seventy-four years of age: which is sufficient to
confirm the stupendious effects thereof; especially in the many
particulars that shall be mentioned as my own discovery with respect
to this excellent remedy, which will perform cures with very little
trouble, and without any charge, and is also to be had wherever
there are any habitations, which can hardly be said of any other: So
that in some sense water may be truly stiled, an universal remedy,
since the diseases it either prevents or cures may have this remedy
applied to all persons, and in all places where men inhabit.
The first commendation of Common Water I shall
Excellency of
Water. mention, is that of Dr Manwaring, in his Method and
means of enjoying health; wherein he saith, that water is a
wholesome drink, or rather the most wholesome—being appointed
for man in his best state; which doth strongly argue that drink to be
the most suitable for human nature—answering all the intentions of
common drinks; for it cools, moistens, and quencheth thirsts; ’tis
clear, thin, and fit to convey the nourishment through the smallest
vessels of the body—and it is a drink that is a rule to itself, and
requires little caution in the use of it, since none will be tempted to
drink of it more than needs: And that, in the primitive ages of the
world, water-drinkers, he says, were the longest livers by some
hundreds of years—not so often sick and complaining as we are.
Digestion to Dr Keill, treating of the stomach, in his Abridgment of
help. the anatomy of human bodies, saith, that water seems
the fittest to promote the digestion of food; all spirituous liquors
having a property by which they hurt, rather than help digestion; the
sad effects of which they are sensible of, he saith, who by a long use
thereof have lost their appetites, hardly ever to be restored without
drinking water, which seldom faileth of procuring a good appetite
and a strong digestion. With which Dr. Baynard agrees, affirming,
“That water liquifies and concocts our food better than any
fermented liquor whatever.” Hist. of cold bathing, p. 440.
Diseases to Dr. Prat, in his treatise of mineral waters, shews it to
prevent. be his judgment, that, if people would accustom
themselves to drink water, they would be more free from many
diseases; such as tremblings, palsies, apoplexies, giddiness, pains in
the head, gout, stone, dropsy, rheumatism, piles, and such like:
which diseases are most common among them that drink strong
drinks, and which water generally would prevent. Moreover, he saith,
that water plentifully drank, strengthens the stomach, causeth an
appetite, preserves the sight, maketh the senses lively, and
cleanseth all the passages of the body, especially those of the
kidneys and bladder.
Health to ’Tis also said by Dr. Duncan, in his treatise of hot
procure by liquors, that, when men contented themselves with
Water. water, they had more health and strength; and that at
this day those who drink nothing but water are more healthy, and
live longer, than those who drink strong liquors, which raise the heat
of the stomach to excess, whereas water keeps it in a due temper.
And he adds in another part of the book, that by hot liquor the blood
is inflamed; and such whose blood is inflamed, live not so long as
those who are of a cooler temper; a hot blood being commonly the
cause of fluxes, rheums, ill digestion, pains in the limbs, head-ach,
dimness of sight, and especially of hysteric vapours. He also imputes
the cause of ulcers to a hot blood, and declares, that if men kept
their blood cool and sweet, by a moderate and cooling diet, they
would never be troubled with ulcers, or other breakings-out. Which
coolness of the blood will be well attained to by drinking a large
draught of water in the morning, which also will carry off the bilious
and salt recrements by urine. And, if water is drank also after dinner,
it will cool a hot stomach, and prevent the rising of those
fermentations which cause wind and belching after meat. So that if
persons who are liable to these disorders will leave off strong liquors
and a hot diet, and drink water, they will procure better health to
themselves than they had before.
Some of the Sir John Floyer also, in his treatise of cold baths, p.
good 109, edit. 5, affirms, that water-drinkers are temperate
properties of
Water.
in their actions, prudent and ingenious; they live safe
from those diseases which affect the head, such as
apoplexies, palsies, pain, blindness, deafness, gout, convulsions,
trembling, madness: And the drinking of water cures the hiccough,
fætor of the mouth, and of the whole body; it resists putrefaction,
and cools burning heats and thirsts, and after dinner it helps
digestion.—And if the virtues of cold water were seriously
considered, all persons would value it as a great medicine, in
preventing the stone, asthma, and hysteric fits; and to the use of
this, children ought to be bred up from their cradles. And, in page
434, he saith, That as water is in chief the universal drink of the
world—so it is the best, and most salubrious. And, in page 434. That
he hath known where a regular drinking of spring-water hath done
considerable cures by washing off the acrid, scorbutic salts from the
blood, and strengthening the coats and fibres of the stomach and
bowels, and hath brought on a good appetite, and a strong
digestion. And I add, that it will infallibly do it in all curable cases.
Cold Water Having read over an old book written by Sir Thomas
strengthenin Elliot, intituled, The castle of health, he there declared
g.
from his own experience, that in the county of
Cornwall, tho’ it was a very cold quarter, the poorer sort, which in his
time did never, or but very seldom, drink any other drinks but water,
were strong of body, and lived to a very great age. To which relation
that of Sir Henry Blunt’s is very agreeable, who affirmed, in his book
of travels into the Levant, (where under the Turkish government the
use of wine was forbid, and where the common drink is water) that
he then had a better stomach to his food, and digested it more
kindly than he ever did before or since.
Digestion And in the treatise of the vanity of philosophy, written
considered. by Dr. Gideon Harvey, it is affirmed, that it is not heat
that causeth a good digestion, but a proper ferment, or liquor
provided by nature, to dissolve the food into a substance like unto
pap made with fine flour; which dissolvent, he saith, is much
depraved by hot spirituous liquors; and therefore he commends
water above all other drinks to promote digestion.
Gout and Water-drinking is also said by Dr. Allen to be good to
Hypochondri prevent two deplorable distempers, the gout and the
ac
Melancholy. hypochondriac melancholy; For, says he, the gout is
generally caused by too great drinking of fermented
liquors, and is never said to have assaulted any drinker of water;
and he saith also, that melancholy hypochondriac is kept off longest
by drinking water instead of strong drink. To which let me add, that I
once knew a gouty gentleman, who, to avoid his drinking
companions in London, retired to New Brentford, where I then lived;
in which town, by a very temperate diet of one meal a day, and
drinking only water, he lived two whole years free from pain: But
being visited by one who came that way, and invited to drink but
one bottle of Claret between them, he fell next day into a terrible fit
of the gout, which held above a month after; of which being
recovered, he by the same course continued well till I left the place,
which was about a year and an half after.
Gravel. The good properties of water are further manifested in
preventing the breeding of gravel in the kidneys; for
Zechias, in Consult. 17. as quoted by Salmon, affirms, that nothing
so much abates the heat of the kidneys, and frees them from those
recrements which cause pain in the back, one great sign of gravel,
as water does; but he adviseth to drink it warm. By the use of
which, he saith, the unnatural heat in time will be so extinguished,
that no more of that matter causing gravel will be produced in the
body. Which assertion by experience I have found to be true; for
observing much gravel to be voided by me, also abundance of
matter floating in the urine like bran; with a great number of
recrements like cuttings of hair, some above an inch long, which
substances were found in all the water that I made in above twelve
months; for which I could get no remedy: I was advised to drink
water, which in about half a year did entirely free me from those
symptoms, which some out of ignorance imputed to witchcraft, so
that from that time to this I never have been troubled with it.
Stone in the Water also is commended as efficacious to prevent the
Bladder. breeding of the stone in the bladder; for it hath been
observed, that in some who have been cut for the stone, that new
stones have been engendered, so that some young persons have
been cut several times. Now, to prevent this, the drinking water hath
been advised with success; for by this that intemperate heat in the
body was abated, which did occasion the distemper. Some have
advised to drink it warm, and others cold, particularly Van Heyden, a
physician of Ghent in Flanders, in his book intituled, Help for the rich
and poor; which, he saith, in p. 40, is sufficiently insinuated by Piso
and Alexander, who assure us, that the taking a draught of cold
water in the morning hath done so much good, that several, after
the voiding of a stone, never had any more stones grew in them.
Stone to Which experiment may give light to the discovery of a
dissolve. way to cure the stone without cutting: For if the
growing of new stones can be prevented by drinking water, let it be
hot or cold, it may prevent a stone from growing bigger when
begun; and if the adding matter to increase a stone new begun, can
be prevented, nature in time may waste that which is begun,
especially if some drops of sweet spirit of nitre be added to all the
water drank, which will powerfully help to cool, and is known to be
an admirable mover or provoker of urine, and will waste a stone,
and make it crumble like fuller’s earth, if applied to a stone taken
from the body. Or the water may be sweetened with honey, which is
now much in use among the gentry, as I am informed by an
ingenious apothecary; who told me, that, among them at present,
pump-water and honey are in great repute to give ease in gravel:
And there is so near an affinity between gravel and the stone, that
what is proper for one, will doubtless be suitable for the other, and
will prevent the growth of both.
Beneficial in Water is also stiled in Senertus’ works, The balsam of
child-bearing. children, the drinking of it by the mother being one of
those things whereby children will be strengthened in the womb,
and will prevent those injuries that are done them by womens
drinking strong liquors; which Samson’s mother was not allowed to
do, for she was commanded not to drink wine or strong drink, Judg.
xiii. 4. But I will not say, if all women should do this, their children
shall be as strong as Samson was; yet this I will say, if they would
do this, they would find their children more free from distempers
and frowardness, and so much more easy to nurse and bring up,
and be less liable to an immature death; the want of which
abstinence from strong drinks, is the cause why so many rich people
find it hard to bring up children, in comparison to what is done by
the poor: For these last are born of mothers who not only are
prevented from being gluttons by their want of dainties, which are
deceitful meat, Prov. xxiii. 3. but they seldom taste wine or strong
drink; whereas the rich not only feed high, but also drink strong
drinks, which in most constitutions do overheat and corrupt the
humours of the body, and that blood by which their children are
nourished during their pregnancy: which injury to unborn infants
would be prevented, if the mother would be temperate in diet, and
drink water, especially at meals, by which the blood of the mother
would be kept cool and clean; which must needs communicate a
healthful substance to the child within her, and prevent all those
distempers which infants bring with them into the world.
Increases And here it may be proper to add, what by divers
milk in experiments it hath been found to be true, that the
women.
drinking water by nurses, while they give suck to
children, will wonderfully increase milk in those that want it, as every
one will find, who can be persuaded to make use thereof. I have
advised many to use it, who have found that, by drinking a large
draught of water at bed-time, they have been supplied with milk
sufficient for that night; when before they wanted it, and could not
be supplied by any other means: And besides, they who have found
their children restless, by reason of too much heat in their milk, do
find them much more quiet after their milk is cooled by water-
drinking.
Stays hunger, By drinking water also the want of food for a time may
and prevents be suffered without starving: For I have been informed
starving.
by a credible friend, who was an officer at sea, that
being sent down to Stafford to see some men conveyed on
shipboard, that had been pressed by act of Parliament for the sea-
service; he found in the prison where they were kept a lusty fellow,
who had declared he would starve himself rather than go to sea;
and, taking particular notice thereof, he found upon due enquiry,
that for twenty days he had refused to eat any manner of food, only
he drank each day about three pints or two quarts of water, hoping
thereby to get himself discharged: But when he found his
pretensions to be in vain, and that in or about two days they should
all march for London, he condescended to eat some food, beginning
with a little; and in the march he was observed to travel as well as
the best man. I find also an account in Dr. Car’s letters, of a certain
crack-brained person, who at Leyden, when the doctor resided in
that university, pretended he could fast as long as Christ did; and it
was found he held out the time of forty days without eating any
food, only he drank water and smoked tobacco. And I once had a
sad complaint from a poor old woman of the greatness of her want,
affirming, that oftentimes she had not eaten any food for two or
three days; upon which I asked her, if she did not then suffer much
uneasiness in her stomach? she said she did; but found a way at last
to asswage her hunger by drinking water, which satisfied her
appetite.
Strengthens Water is also of great use to strengthen weak children;
weak For we are informed by Dr Joseph Brown, in his
children.
treatise of cures performed by cold baths, that the
Welsh women do preserve their children from the rickets, by
washing them night and morning in cold water, till they are three
quarters of a year old, p. 79. And ’tis said by Sir John Floyer, in his
treatise on cold baths, that a lady in Scotland, who had lost several
children thro’ weakness, did, by the advice of a Highland beggar
woman, preserve those she had afterwards, by washing them daily
in cold water. And I myself advised a neighbour, whose child began
to be ricketty, to treat the child in the same manner; but she,
instead of washing, dipped it over head and ears every morning, it
being then in the summer-time: The event of which was, the child
became strong, and had a good countenance, tho’ before it was very
pale and wan: Which shews how great the power of water is, when
used outwardly, to invigorate the spirits, and strengthen nature.
Swellings It is also a known custom, to prevent the swellings
from bruises. that follow bruises in the faces of children, by
immediately applying thereunto a linen cloth four or six times
double, dipped in cold water, and new dipped as it begins to grow
warm; for the cold repels or prevents the flowing of humours to the
part, which otherwise would cause great swelling, and after turn
blackish: And if upon neglecting to do so, a swelling should succeed,
it may be discussed by fomenting night and morning, for an hour at
a time, with water as hot as can be endured; for that will give vent
to the humours to transpire through the skin, or dissolve them, so as
to make them capable of returning back.
All sickness Moreover, by means of water all sickness at the
at the stomach may be cured, which is done thus: Take four
stomach to
cure.
quarts of water, make it as hot over the fire as you can
drink it: of which water let a quart be taken down at
several draughts; then wrap a rag round a small piece of stick, till it
is about the bigness of a man’s thumb; tie it fast with some thread;
and with this, by endeavouring gently to put it a little way down your
throat, provoke yourself to vomit up again most of the water: Then
drink another quart, and vomit up that, and repeat the same the
third and fourth time, if once or twice is not sufficient. You may also
provoke vomiting by tickling your throat with your finger, or the
feather-end of a goose quill; but the cloth round a skewer maketh
one vomit with more ease, which is done with no trouble when the
stomach is full. And by this way of vomiting, which will be all
performed in an hour’s time, that viscous and ropy phlegm in the
stomach, which causeth the sickness, will be cast up, so that the
party in that time will be free from all that inward disturbance, if you
use the remedy at first; but, if the sickness hath continued for a
time, it will require the same course once or twice more, which may
be done in three or four hours, one after another, without any other
inconvenience, besides that of being a little sore in the breast the
next day, which will soon go off by the force of nature. Which
remedy, by forty years experience, I look upon to be infallible in all
sickness at the stomach, from what cause soever, and for all pains in
the belly which seem to be above the navel; for these are all in the
stomach, as by long experience I have found: Which pains are
generally counted the cholic; but it is not so; for true cholics are
always below the navel, in the gut colon. And by this means I have
eased very great pains caused by eating mussels that were
poisonous; and it is also a certain cure for all surfeits or disorders
that follow after much eating. So that the lives of multitudes might
be saved by this means, who, for want of expelling what offends,
often die in misery: For, by thus cleansing the stomach at the first,
the root of diseases proceeding from surfeiting, or unwholsome
food, or any viscous humours from a bad digestion, are prevented;
the stomach being the place in which all distempers at first begin.
No man was more subject to sickness than myself before thirty years
of age; but since I found out the way of vomiting with water, which
is now above forty years, I never have been sick for two days
together: For, when I find myself ill to any great degree, I betake
myself to this way of vomiting, which in an hour’s time restores me
to ease, and perfectly removes my illness. And the same benefit all
my family find in it, as do others also whom I can persuade to try
the experiment, which is such, that no physician whatever can
advise a better to the king himself, should he fall sick. For, in the first
place, it is not a nauseous remedy, it does not make the patient sick,
as the best of all other vomits do; and then it is a vomit which is at
our own command, since we can leave off when we please: And it
infallibly works a cure to all sick stomachs, from whatever cause.
Digestion to Some few indeed pretend they are not able to vomit
cause. by this means: Now, if they cannot vomit, let them
take a pint of water when they find themselves ill from eating, and
do so every three or four hours, eating no more till they are hungry;
and they will find the water digest and carry off what was offensive.
The ingenious Dr. Cheyne, in his Treatise of the gout, affirms, that
warm water drank freely in a morning fasting, and at meals, (and I
say cold water is as good) hath a sovereign remedy for restoring left
appetites, and strengthening weak digestions, when other more
pompous medicines have failed. And he adviseth gouty persons,
after excess either in meat or drink, to swill down as much fair
water, as their stomach will bear, before they go to bed, whereby
they will reap these advantages, either the contents of the stomach
will be thrown up, or both meat and drink will be much diluted, and
the labour and expence of spirits in digestion much saved, p. 44. ed.
4: And indeed I have found by long experience, that nothing causeth
so good a digestion as fair water; but this requires time to free us
from the uneasiness that an ill digestion causeth, whereas vomiting
is an immediate remedy, and frees a man from it upon the spot.
Other We are told by Sir John Floyer, in his Treatise of bath
benefits of and mineral springs, that vomiting with water is very
vomiting with
water.
useful in the gout, sciatica, wind, shortness of breath,
hypochondriac melancholy, and falling-sickness; which
distempers are generally derived from evil matter contained in the
stomach, as is likewise giddiness in the head, and apoplexies, with
which myself once seemed to be threatened: For, after eating a
plentiful dinner, I was seized with giddiness, and the sight of my
eyes became so depraved, that things seemed double, which was
accompanied with a strange consternation of spirit; and having read,
that apoplexies generally seize after eating, I immediately called for
water, and, net daring to stay till it was warmed, I drank it cold, and
by the help of my finger provoked vomiting: Upon which I did
immediately overcome the evils I was threatened with, the
symptoms before-mentioned being the same as did precede the fit
of an apoplexy in another person, as himself afterwards told me,
who died of it the third fit, about a year after.
Shortness of As for people who are troubled with shortness of
breath. breath, it is certain from experience, that vomiting with
warm water three or four times, will afford certain relief. And the
same may be prevented by drinking nothing but water afterwards,
either cold or warmed with a toast. For, upon doing this, the
difficulty of breathing will apparently abate; which water, if you
please, may be boiled with honey. And I knew one, who by this
means, as he was advised by me, lived comfortably in this city two
or three winters, but, having undertaken business which did
occasion drinking strong drinks, was the next winter carried off by
the distemper: Wine, ale, or brandy, being as bad as poison to
people troubled with shortness of breath. So that nothing but water
ought to be drank in that distemper.
Vomiting to Some people are taken with violent vomiting, and the
cure. excess thereof in some hath been so great as to
endanger their lives, yea, cause death: In which case water will be
very helpful; for, if a pint of it warmed be drank after every vomit, it
will prevent that violent straining, wherein lieth the danger of all
vomiting, because to strain violently, when but little will come up,
endangers the breaking of some inward vessel. And, besides this,
the offending matter will be sooner loosened from the internal part
of the stomach, and cast out, upon which the vomiting will sooner
cease: For after this manner the famous Sydenham, a most honest
writer, did overcome the cholera morbus, or vomiting and looseness,
so common in his time, and was found by the weekly bill to kill more
than now die of convulsions; for his way was to boil a chicken in four
gallons of water, which made a broth not such differing from water,
of which he ordered large draughts to be given, and some of it to be
taken by clyster, till the whole quantity was spent, if the vomiting did
not stop before; which did so take off the sharpness of the matter
offending, and wash it out, that the party in a little time became
well. And the same was the practice of Sigismundus Grafius, who
commends pure water in a vomiting or looseness to be drank in
large quantities; for thereby, he saith, the corrosive and sharp
humours will be so weakened, that they will no more offend: And he
saith, it may be drank cold if the patient be strong, otherwise let it
be warmed.
Fluxes. And in common fluxes without vomiting, a quart or
more of warm water drank, will so weaken the
sharpness whereby the distemper is caused, that is will soon be
overcome, and the gripings eased. And in the bloody flux, which is
the most dangerous of all fluxes, the ingenious Cornelius Celsus
adviseth a large drinking of cold water as the best of remedies: But
then no other substance must be taken till the disease is cured. And
Lusitanus, another great physician, affirms, Cent. 1. Obser. 46. that
he knew one, who, being in the summer-time afflicted with the
bloody flux, drank a large quantity of cold water, and thereby
recovered. This large quantity of water, in these fluxes, doth so
correct the sharpness of the humour offending, that it can have no
power to cause pain, or corrode the vessels, and cause bloody
digestions or stools.
Consumption Water also is a drink that conduceth above all things to
s. cure consumptive people; for the digestion being
weakened, is the cause of producing a hot fretting nourishment,
which is injurious to the tender substance of the lungs, and which
constringes and stops up the lymphatic vessels thro’ which the
nourishment is to pass to all the parts, so that by degrees the body
for want of due supplies consumes: Which obstructions, and that
acrimony which causeth them, will be opened and sweetened by the
plentiful use of water, if taken before the lungs become ulcerous.
Which cure of consumptions by water is recommended in the
writings of Dr. Couch, who, in his Praxis Catholica, tells us, that he
knew a man cured very soon of a consumption by drinking pure
water. And it is said by another, that some have been cured of
consumptions by drinking no other drink but water, avoiding all malt
liquors, and sharp wines: For wine or any other strong liquor is
pernicious in this distemper, whose original is affirmed by Dr Coward
to be always in the stomach, from some intemperance in meat or
drink.
Flushes in Some there are who are much troubled with flushing
the face. heat in the face, and others with a heat in the back; in
both which cases, water used as common drink is the best remedy,
with a spare cooling diet: And it is also excellent for such as have
red blotches in their face, which proceed from a hot fretting blood,
which by water-drinking, and a moderate diet, will be kept under:
For as Dr. Duncan, before quoted, doth affirm, those who keep their
blood cool and clean, are never troubled with breakings-out, like
many others, who may be known to be drinkers of hot drinks, and to
use a hot full diet, by their faces being full of blotches.
Cholic. Water is also commended by the learned for the cholic;
large drinking of water hath been found to be an
excellent remedy. And it is said by Fortis, that when he practised at
Venice, he often gave cold water in the cholic, with good success.
With whom an English physician, Dr. Wainwright, in his Mechanical
account of the six non-naturals, concurs; for he saith, that water-
drinkers are never troubled with the cholic, and that many thereby
have been cured, when all other remedies failed: But in this case a
quart at least is required.
Small Pox. And, in the Small Pox, water hath also been proved to
be an excellent drink. Salmon, in his Synopsis
Medicinæ, saith, that in this distemper you may safely give the sick
fair water, of which, says he, they may drink liberally to quench
thirst; the want of which plenty of drink, hath been the death of
many a patient. Which opinion of his was right, as by experience I
have found in two of my own children, when sick of this distemper;
to whom, after I had given a gentle vomit of emetic tartar, I gave no
other drink but water, and they both recovered safely, and were not
in the least light-headed, as two others before were in the same
distemper, when treated otherwise. And I remember that one Dr.
Betts, being consulted in a case where the eruption did not come
out kindly, ordered two quarts of cold water to be drank as soon as
could be, upon which they came out according to expectation, and
the party did well.
Burning It is also certain, that, in what we call burning fevers,
fevers. water is found to be a safe and effectual remedy. It is
said by Dr. Primrose, in his Popular Errors, that many great
physicians have commended the drinking cold water in diseases, and
they attribute to it the chief place in fevers, where the sick must
drink largely; for thus taken it will quench all heat, p. 374. And Galen
is said, by an English author, to reprove Crasistratus for denying cold
water in burning fevers; and says, that this is a remedy for any fever,
provided it be drank in great abundance. With which opinion I find
Dr. Oliver to agree, who, in his Essay on Fevers, says, that in fevers
we must drink oftner than thirst calls for it, and such draughts as are
plentiful; and the drink he prescribes is either cold water or barley-
water. Dr. Wainwright affirms also, that water is proper in fevers, and
that the ancients gave as much of it as the patient could drink. And
by another it is said, that if you give the patient nothing but water
for three days, that in the third day the fever will be cured generally;
but, if it is not, give for food a little barley-broth, and the fever will
not exceed the seventh day. And by another we are informed, how
one in a fever, that was past hope, being forbidden to drink water,
which he greatly desired, did find means, in the absence of his
nurse, to get a large potfull, which he drank off, and lay down again,
being well cooled; after which he fell into a sweat, and so was
cured. Dr. Cook of Warwick, in his book of Observations on English
bodies, prescribes for the cure of fevers, first a vomit, and
afterwards as much cold water as the patient can drink; and he
saith, that, if he sweat upon it, the sweat must be continued as long
as can be. And it is said by another, that it is an excellent remedy in
fevers to drink a quart of hot water, and sweat upon it, being
covered warm. Dr. Quinton, in his book of Observations, writes, that
to one in a malignant fever, whose pulse was so low it could scarcely
be felt, there were three quarts of water given, at several draughts,
to make him vomit; but it did not operate that way, yet the event
was this: It refreshed him much, raised his pulse, brought him into a
breathing sweat, and passed off by urine; which lowness of the
pulse I have often found to be raised in other cases, by drinking
water plentifully. And I know a woman, who, tho’ she in a fever had
the advice of two doctors, yet became distracted; I bid the nurse
give her a pint of cold water, which she drank up, and in three or
four minutes came to her right senses; and desiring to drink more,
she recovered. And I have observed, that when in fevers the patient
can relish no other drink, yet water is always drank with pleasure, as
it also will always be after the eating of sweet things, that spoil the
relish of other drinks; which is one excellence peculiar to water, and
shews it to be most agreeable to the nature of mankind, tho’ now so
much slighted. And, besides this, it is a drink that will not turn sour
in the stomach, as all fermented drinks will do, to the increase of
distempers already begun there, by acidity or sourness.
Gout. And as for the gout, which Dr. Harris saith, in his Anti
Empiric, is gotten either by high feeding or drinking
much wine, or other strong drink; it may be cured, as that author
affirms, by a very spare diet, and drinking water: According to what
is said also by Sir Theodore Mayhern, who, in his Medicinal Counsels,
adviseth to leave off all strong drinks in this disease, and drink only
water. And Van Heyden saith also, in his Treatise of help for the rich
and poor, that there is not any greater remedy for the gout than
drinking water, not only by young, but old men; many of whom, he
saith, have drank cold water for many weeks, which hath succeeded
so well, though they were far gone in years, that they found great
ease thereby, without that offence to the stomach, or hindrance of
digestion, which some did not seem to fear. And he also commends
the large drinking of water in the sciatica or hip-gout, he having
often cured that distemper, by this means, in less time than could
reasonably be expected. And the same I have found to be effectual
in a pain in the shoulder, which had continued very bad for three
months: For, being taken with a fever, I drank in one day about four
quarts of water; which tho’ it did not make me sweat, because I lay
not in my bed, yet it cured me so that I slept well that night; and, in
the morning when I rose, the pain in my shoulder was not felt,
neither did it ever return. And the same success I have had in the
pains of other parts; whereby, I judge, that, in all pains whatever,
the drinking of water is proper, as well as in the gout: And
accordingly I find cold water advised to be drank largely for the cure
of the head-ach from hard drinking; that pain proceeding from the
same cause the gout does, namely, from heat, as all pains do, that
are not from bruises.
Inflammatory It is said also by Dr. Wainwright, that in the itch,
distempers & scurvy, leprosy, and all hot inflammatory distempers,
wind.
such as pleurisies, rheumatisms, and St. Anthony’s fire,
water is a proper remedy; but he adviseth to drink it hot in some
cases, as doubtless it ought to be done in pleurisies. He also saith,
that water is proper in head-achs, catarrhs, vapours, falling-sickness,
dulness of sight, melancholy, shortness of breath, scurvy in the
mouth, and windiness in the stomach: And for this wind in the
stomach, I, by long experience, have found it the best remedy, who
in the former part of my life, through a disorderly diet, and drinking
strong drink like others, was never free from windy belchings, and
sometimes very sickish qualms after meals; from which at length I
was delivered, by drinking only water at meals; so that for above
forty years I have been seldom troubled: And, if I find myself
troubled, a pint or more of cold water, in less than half an hour will
set me free, by drinking of it.
Hard And that water is the best remedy for the mischiefs
drinking. that come by hard drinking, experience teacheth; there
being nothing that so effectually frees from these nauseating and
reaching qualms the next morning, as the drinking a pint or more of
fair water; which effectually allays the inflammation of the bowels,
occasioned by strong or hot drink, which spoils the strength of the
stomach, and of all other parts; nothing being a greater enemy to
the vigour of the nerves and sinews, since by much drinking, men
make themselves unable to stand or go; which effect would never
follow, if liquors that abound with spirits were strengthening; nor
would the fibres of the stomach be so weakened after drinking
strong drinks, as to make men sick; which sickness will soonest be
recovered by the drinking cold water, this being also the best
remedy, if taken largely, for that heat of urine often occasioned by
hard drinking.
Colds and In colds, water is the best of all drinks to prevent
bad floods of rheum from the nose and mouth, as my long
digestion.
experience testifies, and therefore will prevent coughs;
for a cough will seldom succeed a cold, if water is used from the first
as common drink: And if, through neglect, a cough should become
troublesome, the use of water, avoiding all wine and strong drink,
will contribute much to the cure. Some order the water to be drank
warm, but others say, that the drinking it cold vastly excells the
using it hot in a cough. It is said by Van Heydon, that some may
think it strange to advise water in such diseases, which most
account to proceed from crudity or indigestion; but he says, that, in
any disease where the case is dangerous, the use of water is the
only friend to nature; cold being a preventer rather than a cause of
crudity; since by all experience it is proved to be a promoter of good
digestion. And at this time I know a woman, seventy-eight years of
age, who for ten years past hath had a great cough, and spit much
tough phlegm, that this present winter 1722, hath been persuaded
to leave off both strong and small fermented liquor, and drink only
water at meals, and sometimes a dish or two of tea; and hath found
herself much less subject to cough than before, and scarce coughs
at all in bed, tho’ subject before to cough very much in the night:
She also drinks at bed-time half a pint of cold water, and the same
Heart burn. quantity first in the morning, and finds more comfort
by it at so great an age, than wine hath at any time
afforded, Moreover, drinking of water is a certain cure for the heart-
burning; as some affirm.
Strong drinks It is generally the opinion of most physicians, that wine
hurtful to and strong drinks are not proper for children; and that
children.
the smaller and cooler their drink is, the better it will
be with them; and that nothing conduceth more to the health of
children than drinking water, which will prevent the foundation of
those diseases that are caused in many by strong drink, and shew
themselves in their more advanced age, wherein many also suffer
much by the mother’s ill custom of making them gluttons, by
constantly cramming their stomachs with food, many being thereby
destroyed among the children of the rich, before they come to the
years of maturity; when the children of poor country people, who
fare hard, stand their ground till full grown: For fewer children die in
the country than in great cities, where luxury in diet doth more
abound; which is one reason why so few house-keepers in London
were born in it, the great supply of inhabitants being from the
country, children being brought up more hardy there than in London,
where great numbers are killed by over-eating or pleasing their
palates. Which mischief would be in a great measure prevented by
their being accustomed to eat less, and drink water; this by
experience being found to make young children free from that
frowardness, which is commonly caused by a sharp, and hot, or
feverish blood, which engendereth wind, and causeth pain and
gripes: for there is no pain but is the consequence of heat, or inward
as well as outward inflammations.
Fair water To what hath been said may be added this
equal to that consideration, that, when the best physicians are
at Tunbridge.
baffled by some distempers, they advise their patients
to use the water of some mineral spring, tacitly acknowledging
thereby, that all their prescription may be excelled by water. They
pretend indeed to ascribe its effects to some minerals with which the
waters are tinctured: But Dr. Baynard, in p. 438, of Sir John Floyer’s
Cold bathing, tells of a certain person who used to frequent
Tunbridge, by which he found much benefit; but, being hindered
from going thither one season, drank the same quantity of water
taken from the pump of a spring in his own yard, which did him as
much service: whereupon he wrote thus upon his pump:
Steel is a cheat;
’Tis Water does the feat.
And, indeed, if we consider how many diseases and pains proceed
from a sizey, thick blood, which cannot pass as it ought to do
through the finest pipes that convey the blood to the parts, pure
water, without minerals, drank to the quantity of a quart or three
pints in a morning, will attenuate or thin the blood sufficiently:
Nothing, as Boerhaave affirms, being a greater diluter of thick blood,
than warm water drank in great quantity. Which to thin the blood
may be best, tho’ to strengthen the stomach it is best drank cold,
having the same effect inwardly, in some cases, as cold bathing hath
outwardly; its use this way being also great.
Burns and For water I have found, by long experience, to be of
Scalds. excellent use in burns and scalds; for in all burns and
scalds, that are slight, if the part is plunged immediately into cold
water, the colder the better, the pain will instantly be taken off; and
it will fetch out the fire, if continued so long as will be required to do
it by any other remedy. And if the burn be so considerable, that
other remedies must be applied, none of which will take off the
smart of themselves in less than two or three hours; yet if you apply
cold water presently, after other applications are made to the part,
the pain will immediately cease, till the remedy becomes effectual:
So that the ease water will give in such cases, makes it of good use.
Which remedy, as it hath not been discovered till now, appears to
transcend all other remedies in this case; because, in a moment, the
greatest smart will eased, if the water is cold, and will be felt no
more, if the part afflicted be kept immersed in it till the fire is
extinguished, either by the water, or the medicine applied. Besides,
it is a remedy every-where ready at hand, which cannot be said of
any other; which generally requires so much time to get it ready,
that much pain will be endured, if blisters do not arise, which do
much increase the trouble. If the part burnt, or scalded, cannot be
dipped in water, you may apply water to it, with double linen cloths
dipped therein, and new dipped as they grow warm; by which
means I have cured burns and scalds in the face without blistering,
when applied immediately before blisters did arise.
Ulcers from I once knew a large ulcer in the foot, made by the
burnings. running of melted brass into the shoe, that was kept in
hand by a surgeon nine weeks, without any probability of healing,
because of the great inflammation that attended it; but the party,
being a lover of angling, was persuaded to go with some others to
Hackney-river: Some of them went bare-legged into the water, to
come at a certain hole where much fish was sometimes found. The
sport was so good, that the lame man having pulled off his stockings
and plaisters, went in also, where he staid above two hours, and
coming out again, the ulcer, which appeared very red and angry
when he went in, looked pale; he put on his dressings, and came
home, and in less than a fortnight his ulcers healed up; which
doubtless was occasioned by the abating of the inflammation by the
coldness of the water. And I have had an account also from an
acquaintance, that was a surgeon to a merchant ship, that their
gunner, at a time when the captain treated some friends on board,
going to charge a gun that just before had been fired off, the
cartridge he was ramming down took fire, whereby he was blown
into the water, and had some of his fingers torn off, and it was about
an hour before a boat could be got to take him up: But they found
that the coldness of the water had almost stopt the bleeding, and
the cure was effected so speedily, that other surgeons wondered at
it; which he imputed to the water, which kept back the humours, by
its coldness, from flowing to the part at the first: So that there was
no impediment, from inflammation, to hinder healing; for the chief
impediment to healing, is inflammation in wounds or ulcers.
Hot Moreover, to bathe with cold water, is affirmed by Dr.
swellings. Lower to be a sovereign remedy for any hot swelling, if
continued a due time at the first beginning; and it is
affirmed also to be a good cure for the cramp.
Sprains and And as for strains and sprains in the joints, cold water
hot affords the best and most speedy remedy, as Van
swellings.
Heydon affirms; who saith, that, by bathing in cold
water, all harm so received may by this remedy be cured more safely
and more speedily than by any other, without loss of time, cost or
trouble; for no more is to be done, as I have often found, than, as
soon as can be, to put the part into a vessel of cold water for about
two hours, which will prevent all swelling and pain, by repelling or
keeping back the humours that otherwise would flow to the part.
And if it should be the shoulder, or any other part, which is so hurt,
that cannot well be immersed in water after this manner; water may
be applied, by dipping towels folded up into it, and laying them to
Sprains in the part, as is done, in effect, to the wrenched joints of
horses. horses, about which, if you wind oftentimes a thick
rope made of hay, and then cast upon it divers times a
pail of cold water, the wrench will be cured; which experiment is now
commonly practised by those concerned about horses.
Weakness of Bathing in cold water hath also been found to be a
the joints. good remedy to strengthen weakness in the joints, as
Sir John Floyer, in his treatise of Cold Bathing, hath shewed; and
which by experience I found to be true on a certain woman, who
complained of great weakness and pain in her ancles: I advised her
to dip the part in cold water every morning for a quarter of an hour,
and do the same at night; and in about twenty days she became as
strong in that part as she was in the other. And Sir John tells us of a
boy who could not stand, his limbs were so weak, that, by bathing in
cold water, perfectly recovered his strength in a little time.
Pain in the Great pain in the head hath been also cured by this
head. means; for we are told by Van Heydon, that Sir Toby
Matthews had for twenty years been troubled with great pain in one
side of his head, and a great defluxion of rheum from his nose: but
he at last was cured, by applying cold water to the part every day
for about a quarter of an hour: Upon reading of which, I tried the
experiment upon myself, who for a long time had been troubled with
the running of much clear water from my nose, with great spitting of
thin rheum; for I let a water-cock run upon the mould of my head
every morning, by which, in about six weeks time, I was eased of
my trouble. And since that, I had a credible information of a certain
servant maid, who was afflicted greatly with a rheumatism, and an
intolerable pain in the head, who being put into St. Thomas’s

You might also like