Python Web Development with Django®
Total Page:16
File Type:pdf, Size:1020Kb
ptg Python Web Development with Django® ptg Developer’s Library ESSENTIAL REFERENCES FOR PROGRAMMING PROFESSIONALS Developer’s Library books are designed to provide practicing programmers with unique, high-quality references and tutorials on the programming languages and technologies they use in their daily work. All books in the Developer’s Library are written by expert technology practitioners who are especially skilled at organizing and presenting information in a way that’s useful for other programmers. Key titles include some of the best, most widely acclaimed books within their topic areas: PHP & MySQL Web Development Python Essential Reference Luke Welling & Laura Thomson David Beazley ISBN 978-0-672-32916-6 ISBN-13: 978-0-672-32862-6 MySQL Programming in Objective-C ptg Paul DuBois Stephen G. Kochan ISBN-13: 978-0-672-32938-8 ISBN-13: 978-0-321-56615-7 Linux Kernel Development PostgreSQL Robert Love Korry Douglas ISBN-13: 978-0-672-32946-3 ISBN-13: 978-0-672-33015-5 Developer’s Library books are available at most retail and online bookstores, as well as by subscription from Safari Books Online at safari.informit.com Developer’s Library informit.com/devlibrary Python Web Development with Django® Jeff Forcier, Paul Bissex, Wesley Chun ptg Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Cape Town • Sydney • Tokyo • Singapore • Mexico City Many of the designations used by manufacturers and sellers to distinguish their products Editor-In-Chief are claimed as trademarks. Where those designations appear in this book, and the publish- Mark Taub er was aware of a trademark claim, the designations have been printed with initial capital Acquisitions Editor letters or in all capitals. Debra Williams The authors and publisher have taken care in the preparation of this book, but make no Cauley expressed or implied warranty of any kind and assume no responsibility for errors or omis- Development sions. No liability is assumed for incidental or consequential damages in connection with or Editor arising out of the use of the information or programs contained herein. Michael Thurston The publisher offers excellent discounts on this book when ordered in quantity for bulk pur- Managing Editor chases or special sales, which may include electronic versions and/or custom covers and Kristy Hart content particular to your business, training goals, marketing focus, and branding interests. Project Editor and For more information, please contact: Copy Editor U.S. Corporate and Government Sales Jovana (800) 382-3419 San Nicolas-Shirley [email protected] Indexer Cheryl Lenser For sales outside the United States, please contact: Proofreader International Sales Geneil Breeze [email protected] Publishing Visit us on the Web: informit.com/aw Coordinator Kim Boedigheimer Library of Congress Cataloging-in-Publication Data: Cover Designer Forcier, Jeff, 1982- Gary Adair Python web development with Django / Jeff Forcier, Paul Bissex, Wesley Chun. Compositor p. cm. Jake McFarland Includes index. ptg ISBN-10: 0-13-235613-9 (pbk. : alk. paper) ISBN-13: 978-0-13-235613-8 (pbk. : alk. paper) 1. Web site development. 2. Django (Electronic resource) 3. Python (Computer program language) 4. Web sites—Authoring pro- grams. I. Bissex, Paul. II. Chun, Wesley. III. Title. TK5105.8885.D54F68 2009 006.7’6—dc22 2008037134 Copyright © 2009 Pearson Education, Inc. All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited repro- duction, storage in a retrieval system, or transmission in any form or by any means, elec- tronic, mechanical, photocopying, recording, or likewise. For information regarding permis- sions, write to: Pearson Education, Inc Rights and Contracts Department 501 Boylston Street, Suite 900 Boston, MA 02116 Fax (617) 671 3447 ISBN-13: 978-0-13-235613-8 ISBN-10: 0-13-235613-9 Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana. First printing October 2008 ❖ To B r i a n L e v i n e, for introducing me to Python, a small thing that has made a big difference.To my parents, for allowing me to monopolize the family computer while growing up.And to my wife, for her loving support and understanding. —Jeff Forcier To my late father Henry, who taught me to tinker; to my ptg mother Glenda, who taught me to write; and to my wife Kathleen, a brilliant star in my life. —Paul Bissex To my wonderful children, Leanna Xin-Yi and Daylen Xin-Zhi, for whom I’ve had to develop multiple pairs of eyes with which to keep watch over, and who are miraculously able to temporarily transport me back in time to remind me of what childhood and its amazing wonders were like. —Wesley Chun ❖ Table of Contents Introduction 1 Where Web Frameworks Come From 1 A Better Way 2 We’re Not in Kansas Anymore 2 Web Development Is Better with Python and Django 3 I: Getting Started 1 Practical Python for Django 7 Python Skills Are Django Skills 7 Getting Started: Python’s Interactive Interpreter 8 Python Basics 10 Comments 10 Variables and Assignment 10 Operators 11 ptg Python Standard Types 11 Object Boolean Values 12 Numbers 12 Numeric Operators 13 Numeric Built-in and Factory Functions 14 Sequences and Iterables 14 Lists 17 Strings 19 Sequence Built-ins and Factory Functions 25 Mapping Type: Dictionaries 26 Standard Type Summary 28 Flow Control 28 Conditionals 29 Loops 29 Exception Handling 30 The finally Clause 31 Throwing Exceptions with raise 32 Files 33 Functions 34 Declaring and Calling Functions 34 Functions Are First-Class Objects 36 Anonymous Functions 38 *args and **kwargs 40 Decorators 42 Object-Oriented Programming 44 Class Definitions 44 Instantiation 45 Subclassing 46 Inner Classes 46 Regular Expressions 47 The re module 47 Searching Versus Matching 48 Common Gotchas 48 Single-Item Tuples 48 Modules 48 Mutability 50 Constructor Versus Initializer 52 ptg Coding Style (PEP 8 and Beyond) 53 Indent Four Spaces 53 Use Spaces and Not Tabs 53 Don’t Write Single-Line Suites on the Same Line as the Header 54 Create Documentation Strings (aka “docstrings”) 54 Summary 55 2 Django for the Impatient: Building a Blog 57 Creating the Project 58 Running the Development Server 59 Creating the Blog Application 61 Designing Your Model 62 Setting Up the Database 62 Using a Database Server 63 Using SQLite 63 Creating the Tables 64 Setting Up the Automatic admin Application 65 Tr ying Out the admin 66 Making Your Blog’s Public Side 70 Creating a Template 70 Creating a View Function 71 Creating a URL Pattern 72 Finishing Touches 73 Template Niceties 73 Date-Based Ordering 74 Timestamp Formatting Via a Template Filter 75 Summary 75 3 Starting Out 77 Dynamic Web Site Basics 77 Communication: HTTP, URLs, Requests, Responses 78 Data Storage: SQL and Relational Databases 78 Presentation: Rendering Templates into HTML and Other Formats 79 ptg Putting It All Together 79 Understanding Models, Views, and Templates 79 Separating the Layers (MVC) 79 Models 80 Views 81 Templates 81 Overall Django Architecture 82 Core Philosophies of Django 82 Django Tries to Be Pythonic 84 Don’t Repeat Yourself (DRY) 84 Loose Coupling and Flexibility 84 Rapid Development 85 Summary 86 II: Django in Depth 4 Defining and Using Models 89 Defining Models 89 Why Use an ORM? 89 Django’s Rich Field Types 91 Relationships Between Models 93 Model Inheritance 97 Meta Inner Class 100 Admin Registration and Options 101 Using Models 102 Creating and Updating Your Database Using manage.py 103 Query Syntax 104 Utilizing SQL Features Django Doesn’t Provide 112 Summary 116 5 URLs, HTTP Mechanisms, and Views 117 URLs 117 Introduction to URLconfs 117 Replacing Tuples with url 119 Using Multiple patterns Objects 119 ptg Including Other URL Files with include 120 Function Objects Versus Function-Name Strings 121 Modeling HTTP: Requests, Responses, and Middleware 122 Request Objects 123 Response Objects 125 Middleware 126 Views/Logic 127 Just Python Functions 128 Generic Views 128 Semi-generic Views 130 Custom Views 131 Summary 133 6 Templates and Form Processing 135 Templates 135 Understanding Contexts 135 Template Language Syntax 136 Forms 142 Defining Forms 142 Filling Out Forms 147 Validation and Cleaning 149 Form Display 150 Widgets 152 Summary 154 III: Django Applications by Example 7 Photo Gallery 159 The Model 160 Preparing for File Uploads 161 Installing PIL 162 Testing ImageField 163 Building Our Custom File Field 164 Initialization 166 Adding Attributes to the Field 167 Saving and Deleting the Thumbnail 168 Using ThumbnailImageField 169 ptg Setting Up DRY URLs 169 The Item App’s URL Layout 172 Tying It All Together with Templates 173 Summary 179 8 Content Management System 181 What’s a CMS? 181 The Un-CMS: Flatpages 182 Enabling the Flatpages App 182 Flatpage Templates 184 Testing It Out 184 Beyond Flatpages: A Simple Custom CMS 185 Making the Model 186 Imports 188 Completing the Model 188 Controlling Which Stories Are Viewed 189 Working with Markdown 190 URL Patterns in urls.py 192 Admin Views 193 Displaying Content Via Generic Views 196 Template Layout 196 Displaying Stories 198 Adding Search 199 Managing Users 201 Supporting Workflow 202 Possible Enhancements 202 Summary 203 9 Liveblog 205 What Exactly Is Ajax? 205 Why Ajax Is Useful 206 Planning the Application 206 Choosing an Ajax Library 207 Laying Out the Application 208 Putting the Ajax In 211 The Basics 212 The “X” in