Tải bản đầy đủ (.pdf) (408 trang)

IT training beginning django e commerce mcgaw 2009 10 28 1

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.12 MB, 408 trang )

  CYAN
  MAGENTA

 YELLOW
  BLACK

Books for professionals by professionals ®

Beginning Django E-Commerce
Dear Reader,

Jim McGaw
Companion eBook

THE APRESS ROADMAP
Beginning Django
E-Commerce

Definitive Guide to Django,
2nd edition

Pro Django

Companion
eBook
Available

Beginning

Django E-Commerce


Django is a web framework that allows developers to build clean and elegant
web sites. In this book we take an in-depth and detailed look at using Django to
build a fully functional e-commerce web site. Whether you’re a seasoned web
programmer looking to try Django or completely new to the realm of dynamic
web development, this book will give you the theoretical groundwork and practical guidance you need to develop your ideas into a working site. Best of all,
Django and Python are open source, so they’re free for anyone to use.
As a developer, I have always enjoyed learning new things by example. For
this reason, we will build a single shopping cart site over the course of this book.
Chapter by chapter, we’ll add new features and functionality to the site, all the
while discussing the theory behind the code we’re writing. In the end, our site
will have a product catalog, shopping cart, checkout functionality, payment
gateway integration, customer accounts, order administration, product search,
cross-selling, automated test cases, and secure credit card storage. You’ll see
how all of these individual pieces fit together to create a search engine-friendly
site, learn Django best practices in the process, and come away with a code
base that you can re-use in your other projects.
Because Django was created using the Python programming language, you
get the benefit of several solutions to existing problems that have been put forth
by the heavily active Python community on the web. As a language, Python is
very powerful, and because of this, there is almost no limit to the kinds of sites
you can build, the complexity of which is all made simple using Django. After
learning the concepts covered in this book, you’ll be well on your way to developing your own fully featured, production-ready Django web sites.
Have fun developing along with this book!

The EXPERT’s VOIce ® in Web Development

Beginning

Django
E-Commerce

Learn how to build powerful e-commerce sites
using the Django web framework and the Python
programming language

See last page for details
on $10 eBook version

Practical Django Projects,
2nd edition

www.apress.com

)3".




   

US $44.99

McGaw

SOURCE CODE ONLINE

Jim McGaw

Shelve in
Web Development / General
User level:

Beginner to Intermediate

  

this print for content only—size & color not accurate

trim = 7.5" x 9.25"  spine = 0.75"  408 page count


Beginning Django
E-Commerce

■■■
JIM MCGAW


Beginning Django E-Commerce
Copyright © 2009 by Jim McGaw
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 (pbk): 978-1-4302-2535-5
ISBN-13 (electronic): 978-1-4302-2536-2
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.
Lead Editor: Duncan Parkes
Development Editor: Douglas Pundick
Technical Reviewer: George Vilches

Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Tony Campbell, Gary Cornell,
Jonathan Gennick, Michelle Lowman, Matthew Moodie, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick,
Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh
Coordinating Editor: Jim Markham
Copy Editor: Ralph Moore
Compositor: Mary Sudul
Indexer: Carol Burbo
Artist: April Milne
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 , or visit
.
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 , or visit .
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 />The information in this book is distributed on an “as is” basis, without warranty. Although every precaution 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 indirectly by the information contained
in this work.
The source code for this book is available to readers at . You will need to answer questions
pertaining to this book in order to successfully download the code.


This book is dedicated to my parents.
—Jim McGaw



■ CONTENTS


Contents at a Glance
■About the Author .................................................................................................... xi
■About the Technical Reviewer ............................................................................... xii
■Acknowledgments ................................................................................................ xiii
■Introduction .......................................................................................................... xiv
■Chapter 1: Best Laid Plans.......................................................................................1
■Chapter 2: Creating a Django Site..........................................................................17
■Chapter 3: Models for Sale ....................................................................................39
■Chapter 4: The Shopping Cart................................................................................79
■Chapter 5: Site Checkout & Orders ......................................................................109
■Chapter 6: Creating User Accounts......................................................................153
■Chapter 7: Product Images..................................................................................173
■Chapter 8: Implementing Product Search ...........................................................179
■Chapter 9: Intelligent Cross-Selling.....................................................................193
■Chapter 10: Adding in Ajax ..................................................................................205
■Chapter 11: Search Engine Optimization .............................................................231
■Chapter 12: Web Security Overview ....................................................................255
■Chapter 13: Improving Performance ...................................................................279
■Chapter 14: Django Testing .................................................................................299
■Chapter 15: Deployment ......................................................................................323
■Chapter 16: Django on Google App Engine ..........................................................341
■Index....................................................................................................................365

v


vi


■ CONTENTS


Contents
■About the Author .................................................................................................. xvi
■About the Technical Reviewer ............................................................................. xvii
■Acknowledgments .............................................................................................. xviii
■Introduction .......................................................................................................... xix
■Chapter 1: Best Laid Plans.......................................................................................1
Selling Stuff Online ........................................................................................................................ 2
Why Django? .................................................................................................................................. 4
Straying From the Django Philosophy ....................................................................................... 5
A Quick Word on the Software .................................................................................................. 5
A Note on Version Control.......................................................................................................... 6
Firefox ....................................................................................................................................... 6
Installing the Software ................................................................................................................... 7
Installing Python........................................................................................................................ 7
Installing Django........................................................................................................................ 8
Installing MySQL........................................................................................................................ 9
Installing Eclipse and the PyDev Extensions ............................................................................. 9
Things to Consider Before You Start .............................................................................................. 9
Security ................................................................................................................................... 10
Accessibility ............................................................................................................................ 10
PCI Compliance........................................................................................................................ 11
Search Engine Optimization .................................................................................................... 11
Deployment ............................................................................................................................. 12
Business Requirements ............................................................................................................... 12
Accounting & Auditing ............................................................................................................. 12
Supply Chain Management...................................................................................................... 13
Marketing Decisions................................................................................................................ 14
Summary...................................................................................................................................... 16


vii


■ CONTENTS

■Chapter 2: Creating a Django Site..........................................................................17
A Django-istic Welcome ............................................................................................................... 17
Creating the Project................................................................................................................. 17
What Django Creates............................................................................................................... 18
Creating the MySQL Database ..................................................................................................... 19
Dealing with Django Exceptions................................................................................................... 22
Template & View Basics............................................................................................................... 23
Advanced Templates with Inheritance......................................................................................... 25
Greater Ease with render_to_response() ..................................................................................... 28
Adding in the CSS ........................................................................................................................ 29
Location, Location, Location ........................................................................................................ 34
A Site Navigation Include ............................................................................................................. 35
A Word (or Two) About URLs ........................................................................................................ 37
Summary...................................................................................................................................... 38

■Chapter 3: Models for Sale ....................................................................................39
Databases 101 ............................................................................................................................. 40
An Introduction To SQL............................................................................................................ 40
What Makes a Relational Database......................................................................................... 42
What Django Gives You – The ORM.............................................................................................. 44
Creating the Catalog App ............................................................................................................. 45
Creating the Django Models......................................................................................................... 46
Model Field Data Types ........................................................................................................... 48
Creating the Category Model................................................................................................... 50
Creating the Product Model..................................................................................................... 54

The Django Admin Interface......................................................................................................... 56
Product and Category Admins ................................................................................................. 57
A Note on Model Validation ..................................................................................................... 59
Syncing Up the Models............................................................................................................ 60
Playing with Model Structure and Data................................................................................... 64
Templates, URLs, and Views........................................................................................................ 65
Configuring Page Titles and Meta Tags................................................................................... 66
Coding Up the Catalog Views................................................................................................... 68
Creating the Template Files..................................................................................................... 69
A Category Link List................................................................................................................. 73

viii


■ CONTENTS

Our Code in Review...................................................................................................................... 73
So How Does It All Work? ........................................................................................................ 75
File Not Found and Custom 404s............................................................................................. 77
Summary...................................................................................................................................... 78

■Chapter 4: The Shopping Cart................................................................................79
Shopping Cart Requirements ....................................................................................................... 79
An Introduction to Sessions ......................................................................................................... 80
The Shopping Cart Model ........................................................................................................ 82
Django Sessions Overview ...................................................................................................... 84
Enabling and Using Sessions .................................................................................................. 85
Using Django Forms ..................................................................................................................... 86
The Add To Cart Form.............................................................................................................. 86
Processing the Form ............................................................................................................... 88

Putting It All Together.............................................................................................................. 89
Cart Form Code in Review ....................................................................................................... 94
Creating the Shopping Cart Page ................................................................................................. 95
Django Template ‘if’ and ‘for’ Tags ......................................................................................... 96
Custom Template Filters ......................................................................................................... 96
Creating the Cart Page ............................................................................................................ 97
Adding Custom Template Tags .................................................................................................. 101
Re-creating the Category List Tag......................................................................................... 103
Static Content with Flatpages ............................................................................................... 105
Navigation Tags..................................................................................................................... 107
Summary.................................................................................................................................... 108

■Chapter 5: Site Checkout & Orders ......................................................................109
Google Checkout API .................................................................................................................. 109
Signing up with Google Checkout.......................................................................................... 110
Submitting Orders to Google ................................................................................................. 111
Building XML Documents in Python....................................................................................... 112
Making HTTP Requests in Python.......................................................................................... 114
Your Google Merchant ID and Key ......................................................................................... 115
The Python Property Decorator ............................................................................................. 115
Creating the Checkout App.................................................................................................... 116

ix


■ CONTENTS

Order Checkout Requirements................................................................................................... 124
SSL Middleware .................................................................................................................... 124
DRY Models and Forms ......................................................................................................... 126

Secure HTTP Requests .......................................................................................................... 128
Credit Card Transactions ....................................................................................................... 129
Order Checkout by Django ......................................................................................................... 130
Signing up for an Authorize.Net Test Account....................................................................... 130
Order Information Models...................................................................................................... 131
The Checkout Form ............................................................................................................... 133
Authorization and Capture..................................................................................................... 137
Order Processing ................................................................................................................... 139
Checkout Views and URLs ..................................................................................................... 141
Checkout Template and Order Form ..................................................................................... 143
Order Administration ............................................................................................................. 149
Summary.................................................................................................................................... 151

■Chapter 6: Creating User Accounts......................................................................153
Making Friends with the Source ................................................................................................ 153
Hooking Into Django’s Authentication ........................................................................................ 154
Creating the Login & Registration Pages............................................................................... 156
The My Account Page............................................................................................................ 160
The Change Password Page.................................................................................................. 162
The Order Details Page.......................................................................................................... 163
Django User Profiles................................................................................................................... 165
Abstract Base Classes........................................................................................................... 165
The Order Info Page............................................................................................................... 167
Updating the Checkout Page ................................................................................................. 169
Summary.................................................................................................................................... 171

■Chapter 7: Product Images..................................................................................173
Dealing with Images .................................................................................................................. 173
Django Image Fields .............................................................................................................. 174
Installing the Python Imaging Library.................................................................................... 174

Database Changes................................................................................................................. 174
Editing the Model................................................................................................................... 175

x


■ CONTENTS

Adding a New Image ............................................................................................................. 176
Image Template Changes........................................................................................................... 177
Summary.................................................................................................................................... 178

■Chapter 8: Implementing Product Search ...........................................................179
Instant Search............................................................................................................................ 179
Search Requirements................................................................................................................. 180
Model Managers.................................................................................................................... 180
Complex Lookups with Q ....................................................................................................... 182
Search Results Pagination..................................................................................................... 183
Implementing Search................................................................................................................. 184
The Search Module................................................................................................................ 185
Search Template Tags........................................................................................................... 187
Search View and Template.................................................................................................... 189
Third-Party Search Solutions ..................................................................................................... 192
Summary.................................................................................................................................... 192

■Chapter 9: Intelligent Cross-Selling.....................................................................193
Product Page Recommendations ............................................................................................... 193
Order-Based Filtering ............................................................................................................ 194
Customer-Based Order Filtering............................................................................................ 195
A Hybrid Approach................................................................................................................. 195

Home Page Recommendations .................................................................................................. 196
Tracking Each User................................................................................................................ 197
Dealing with Searches........................................................................................................... 198
View-Based Recommendations............................................................................................. 200
Building the Homepage.............................................................................................................. 202
Summary.................................................................................................................................... 204

■Chapter 10: Adding in Ajax ..................................................................................205
The Ajax Pros and Cons ............................................................................................................. 205
How Ajax Works ......................................................................................................................... 207
jQuery for Ajax............................................................................................................................ 208
Getting jQuery........................................................................................................................ 208
jQuery Basics......................................................................................................................... 209

xi


■ CONTENTS

JavaScript Object Notation.................................................................................................... 211
Making Ajax Requests ........................................................................................................... 212
Product Reviews ........................................................................................................................ 213
Review Model and Form........................................................................................................ 213
Template and View Changes ................................................................................................. 214
The Ajax Part of this Equation ............................................................................................... 216
Adding a Product Review ...................................................................................................... 219
Product Catalog Tagging............................................................................................................ 220
Getting Django-Tagging......................................................................................................... 220
Django Content Types............................................................................................................ 221
Enabling Product Tagging ..................................................................................................... 222

Creating the Tag Cloud .......................................................................................................... 224
JavaScript Finishing Touches .................................................................................................... 226
Summary.................................................................................................................................... 229

■Chapter 11: Search Engine Optimization .............................................................231
The Importance of Inbound Links............................................................................................... 232
Content is King........................................................................................................................... 233
Title and Meta Tags ............................................................................................................... 233
Keywords in URLs.................................................................................................................. 234
Generating a Keyword List .................................................................................................... 235
The Duplicate Content Problem............................................................................................. 236
Semantic Web - Microformats & RDFa.................................................................................. 238
Launching the Site ..................................................................................................................... 240
Submit Your URL.................................................................................................................... 240
robots.txt File......................................................................................................................... 241
Sitemaps for Search Engines ................................................................................................ 242
Content Relocation ................................................................................................................ 244
Google Webmasters ................................................................................................................... 245
Google Analytics......................................................................................................................... 246
The Data Warehouse Principle .............................................................................................. 247
Signing Up for Google Analytics ............................................................................................ 248
E-Commerce and Search Tracking........................................................................................ 248
Google Base Product Feed ......................................................................................................... 251
500 Server Errors ....................................................................................................................... 253

xii


■ CONTENTS


Summary.................................................................................................................................... 253

■Chapter 12: Web Security Overview ....................................................................255
Securing the Site From Within ................................................................................................... 255
Django Permissions............................................................................................................... 256
Applying Permissions to Users ............................................................................................. 257
Applying Permissions to Groups............................................................................................ 257
Protecting Against External Attacks........................................................................................... 258
The Evils of Debug Mode ....................................................................................................... 258
Configuring Local Settings .................................................................................................... 259
Customer Registration Revisited ........................................................................................... 259
Cross-Site Scripting Attacks.................................................................................................. 262
What’s in a QueryString?....................................................................................................... 263
Cross-Site Request Forgery................................................................................................... 263
SQL Injection ......................................................................................................................... 265
Moving the Admin Interface .................................................................................................. 266
Storing Secrets .......................................................................................................................... 266
Storing Customer Passwords ................................................................................................ 267
Storing Credit Card Data........................................................................................................ 269
Symmetric Cryptography....................................................................................................... 270
Google Keyczar...................................................................................................................... 271
A Credit Card Model and Form .............................................................................................. 273
Summary.................................................................................................................................... 278

■Chapter 13: Improving Performance ...................................................................279
The Database ............................................................................................................................. 280
Searching your Models.......................................................................................................... 280
Avoiding Expensive Joins ...................................................................................................... 281
Creating Database Indexes.................................................................................................... 283
Deleting Old Data................................................................................................................... 284

Caching with Memcached.......................................................................................................... 287
The Virtue of Stale Data......................................................................................................... 287
Template Caching.................................................................................................................. 288
The Low-Level Cache API ...................................................................................................... 289
Django Signals for Cache Invalidation................................................................................... 291

xiii


■ CONTENTS

A Quick Word about Django Signals ...................................................................................... 293
Front-End Engineering ............................................................................................................... 293
Move CSS and JavaScript Into Separate Files....................................................................... 295
Reduce the Number of External Components........................................................................ 295
Optimize External Components ............................................................................................. 296
Summary.................................................................................................................................... 297

■Chapter 14: Django Testing .................................................................................299
Why We Test .............................................................................................................................. 299
How to Test Code .................................................................................................................. 300
Creation of the Test Database ............................................................................................... 301
Python & Django Test Methods ............................................................................................. 301
Anatomy of a Test Class ........................................................................................................ 303
Testing the Product Catalog....................................................................................................... 304
Writing Functional Tests........................................................................................................ 304
Managing Test State with Fixtures........................................................................................ 307
Category Testing.................................................................................................................... 309
Testing the ActiveProductManager ....................................................................................... 312
Product Catalog Model Tests ..................................................................................................... 313

Testing Forms & Shopping Cart ................................................................................................. 315
Testing the Checkout Form ........................................................................................................ 318
Security Testing ......................................................................................................................... 319
Summary.................................................................................................................................... 321

■Chapter 15: Deployment ......................................................................................323
The Django Philosophy............................................................................................................... 324
Finding a Hosting Plan ............................................................................................................... 325
Phase One: Apache and mod_wsgi............................................................................................ 326
Installing the Apache Web Server ......................................................................................... 326
Creating the mod_wsgi File and Apache Virtual Host ........................................................... 328
Phase Two: Nginx for Static Media ............................................................................................ 331
Installing and Configuring NginX ........................................................................................... 331
Updating the Apache Virtual Host.......................................................................................... 333
Phase Three: Configuring SSL.................................................................................................... 334
Transferring Data with Django ................................................................................................... 338

xiv


■ CONTENTS

The Admin Interface Styles ........................................................................................................ 338
Summary.................................................................................................................................... 339

■Chapter 16: Django on Google App Engine ..........................................................341
The Inconvenient Truth .............................................................................................................. 342
Signing Up For An Account ........................................................................................................ 342
The Django App Engine Patch .................................................................................................... 343
Getting the Test Page Running................................................................................................... 346

Our Google App Engine Store ..................................................................................................... 346
The Brubeck Shopping Cart App ................................................................................................ 353
Views and Templates ................................................................................................................. 356
Managing Database Indexes ...................................................................................................... 361
Error Logs, Remote Data API, and Network Programming......................................................... 362
Summary.................................................................................................................................... 364

■Index....................................................................................................................365

xv


■ CONTENTS

About the Author
■Jim McGaw is a web developer with several years experience developing datadriven web applications, particularly search-engine—friendly online catalog and
shopping cart sites. He's very thankful that he gets to be a web developer for a
living, and is a security, accessibility, and usability advocate. Despite his technical
background, he remains in awe of people who are able to design web sites that are
visually stunning.
Currently, he lives and works as a software engineer in Santa Barbara,
California, where he enjoys hiking, ocean kayaking, and playing the guitar in his
spare time. To send him feedback, comments, or questions, drop him a line at:


xvi


■ CONTENTS


About the Technical Reviewer
■George Vilches is a software engineer and systems administrator with an
unabashed fondness for Python and the web in both disciplines. In the last three
years, he has made several contributions to Django, with a focus on the ORM and
administrative side of things. He was a principal engineer with Propeller
(), and continues to build Django applications with
Fortune Cookie Studios, ().
George's personal time is split evenly over tinkering with open source
projects and enjoying the company of his wife Kate, corgi and two cats, all of
whom would prefer he stop tinkering and attend to them more.

xvii


■ CONTENTS

Acknowledgments
A good deal of effort other than my own went into the writing of this book, and I’m grateful to all who
helped. Most notably, I'd like to thank the technical reviewer, George Vilches, for his valuable
contributions to this book. George strikes me as an extremely knowledgeable person in several different
areas as well as a tireless worker, and he really contributed a lot of valuable suggestions. His efforts in
reviewing this book are probably near-deserving of co-author credit, and I thank him.
I'd like to thank those on the Apress staff with whom I worked directly, namely James Markham,
Duncan Parkes, and Douglas Pundick, whose efforts brought this book together, and to Ralph Moore,
who transformed the grammatical sludge of the original writing into a much more readable text. I'd also
like to extend my thanks to those people whose names I won't know until I see them on the copyright
page of this book in print. That being said, while I had a lot of help, the occasional error might still be
lurking in the text. These errors are my fault and not theirs.
I owe a debt of gratitude to my friend Mark Pellerito, who initially got me started doing computer
programming, and was always there to answer all the technical questions spewing forth from my

knowledge-hungry brain. I'm in this whole mess because of you. Thanks.
Lastly, I’d like to thank Tara, who supported and endured me the whole time I was writing this book.
Thanks for making me the luckiest guy on the planet.

xviii


■ INTRODUCTION

Introduction
I read a lot of technical books about software and computer programming. This isn't because I have a
great fondness for reading, nor do I actually like owning a massive collection of computer books that's
slowly beginning to overtake every room in my home. I do it because at any given time, I'm usually
working on a programming project and am faced with a dozen problems that I need to solve. These
unsolved problems fester in my head. They scrape away at the surface of my brain like jagged rusty metal
hooks. These books provide me sweet relief from these pains.
In my experience, there are two types of computer books: those that act as reference guides and
those that act as tutorials. This book falls squarely in the latter category. While you need both tutorial
and reference books in order to learn something, I tend to like tutorial books better, simply because they
aid you in making better use of the reference books. For this reason, over the course of this book, we will
be building one single Django project, to which we will add new features with each chapter and learn
new parts of the Django web framework as we go.
There are lots and lots of Django apps floating around on the web. Many of these will contain
perfectly good–and in some cases, absolutely spectacular–working code that you can use on your site.
In other cases, the code is less than great, but still works. While I've taken a snippet of code from the
open source community here and there throughout this book, I've mostly gone the do-it-myself route
and implemented things from scratch. The reason for this is simple: when you're learning, rolling your
own solutions at a lower level instead of just plugging in an app you found ready-made on Google Code
or Django Snippets is much better for making the basic concepts stick to your brain. The drawback of
this approach, of course, is that there are parts of the site we're going to develop in this book that are

greatly simplified.
However, when you use snippets of code samples that are posted in various corners of the Internet
by people all over world, you will still encounter problems. You'll get weird errors when you hook the
new code into your site, and you'll end up having to read the Django docs and Django blogs and Django
books to determine what's going wrong. My hope is that, after working through the examples in this
book, you'll not only be much more adept at developing complex and powerful code with Django from
scratch, you'll also have a much better grasp of dealing with these kinds of integration problems with
existing third-party solutions when they arise. On top of this, you might also find yourself working to
extend the functionality of an existing solution to suit your own needs, which is a good ability to have as
well.

Who This Book Is For
This book is aimed at developers who are interested in learning more about the process of how to create
a Django web site. Over the course of the book, we're going to create a single working e-commerce web
site that we'll deploy into production at the very end. In each chapter, we'll tackle a particular feature or
group of features that we want to add to the site, outline the requirements and discuss the related
concepts, and then write code to implement each feature using Django. This will allow you to see how
the different parts of a single Django project all fit together. In the end, you'll have a thorough grasp of

xix


■ INTRODUCTION

how a Django web application is created, secured, optimized for search engines, tested, and finally
deployed.
We're going to create a shopping cart site in this book, and while some of the sections cover
problems that are specific to e-commerce web sites, most of the content has applications to other types
of sites as well. For example, Chapter 8 covers implementation of internal site search so that customers
can find things in our product catalog. Search functionality is a requirement of almost any data-driven

web site. In Chapter 4, we create a shopping cart for our product catalog, allowing customers to
aggregate products before they check out, and here you'll learn more about how you can use Django
sessions in order to track information about your customers, whether or not they are logged in. The
checkout functionality created in Chapter 5 covers the basics of Python network programming in order
to integrate with third-party payment gateways, and the material covered is useful to anyone interested
in integrating Django with web services.
This book does assume familiarity with the Python programming language. If you're a complete
beginner and have never worked with Python, don't worry... it's a very simple language and you'll be
able to catch on very quickly. If you're new to programming and would like an introduction, I'd suggest
you take a look at Beginning Python: Second Edition, by Magnus Lie Hetland (Apress, 2008). If you're
already familiar with at least one other programming language and just need to get caught up on the
syntax of Python, I can heartily recommend you read Dive Into Python, by Mark Pilgram (Apress, 2004).

The Web Sites In This Book
In this book, I'm going to build a fictional e-commerce site that sells musical instruments and sheet
music. The name of the site is "Modern Musician." Developers in the Django community have a
penchant for naming their apps and projects after old-time musicians, like John Coltrane, Louis
“Satchmo” Armstrong, and Duke Ellington. This tradition was started by the creators of the Django web
framework, who chose to name it after guitarist Django Reinhardt, who is regarded by many as one of
the greatest jazz guitarists of all time.
It didn’t dawn on me until around the time I started writing Chapter 13 that the name "Modern
Musician" might be construed as a tongue-in-cheek reference to this tradition in the Django
community. In my defense, I originally created the Modern Musician e-commerce site in PHP, as a
demo e-commerce site. Later, I implemented roughly the same Modern Musician site using Ruby on
Rails, for the sole purpose of learning Rails. So when I got around to spawning this little project in
Django, the last thing on my mind when naming the project was any attempt at ridicule. I did so out of
tradition.
In the first 15 chapters of this book, we’re going to build a single e-commerce web site. For those
interested, the site we’re going to create is available for public viewing at While an administrative interface is part of the site that we’re going to create in this book,
the public site does not permit altering of data in the product catalog.

In Chapter 16, when we look at putting Django projects up on the Google App Engine, we’re going to
create a minimal shopping cart site, which is also available for public viewing at />
Source Code and Errata
We’re going to write a lot of code in this book. It’s not an overbearing amount, as Python is a very
concise language and Django syntax tends to reduce the amount of repetitive code that you need to
write. In spite of this, you still might find yourself wanting to have a copy of the code on hand so that you

xx


■ INTRODUCTION

don’t have to type in every last line. The source code for the site we’re going to create in this book is
available for download from the Apress web site.1 (There’s also a bunch of awesome books on there.)
If you happen to be reading a digital version of this book on your computer and have the option of
selecting text, I’d be careful about copying code from your screen into your editor. Some characters
might not transfer from electronic versions of this book into IDEs very well, as they might confuse the
Python interpreter. You’re much safer just typing it in yourself. You’ve been warned.
Lastly, while everyone has worked really hard to ensure that this book is grammatically and
technically correct, some grammatical and technical “bugs” may have slipped in under our reviewing
eyes. (“Bug” is a nice euphemism for “mistake,” isn’t it?) If you find an error and would like to politely
rub it in my face, please feel free to submit it to this book’s errata page on the Apress web site.2
If you’d like to contact me with any questions or concerns you have about the content of this book,
shoot me an e-mail at:

1
2

/> />
xxi




CHAPTER 1
■■■

Best Laid Plans
Web development starts in the mind. Sure, it may be done in Python, Ruby, C#, Groovy, or any of the
other myriad programming languages out there these days, but all of them are just tools. The code for
web sites is created in the mind. Conception occurs in the space (or lack of empty space, hopefully)
between your ears, and implementation occurs in your programming language of choice.
One of the main goals of this book is to teach you how to architect a site using the Django web
framework. But architecting a site, like any piece of software you might be developing, is about a
sequence of decisions you need to make for yourself. Some of these decisions are small; others are quite
large. A lot of them don’t have an easy answer or one that is immediately obvious.
While I can’t answer your questions for you, and even though my decisions might end up very
different from your own, I’m going to talk you through the process. In this way, I hope to show how to
translate your train of thought, and the decisions you make along the way, into workable software. And I
hope that it makes you some money in the process.
In this book, we’re going to develop an e-commerce application. I chose this kind of web site for a
few reasons. First, there is money in selling products online. It’s still very possible for would-be
entrepreneurs to conceive of business plans that are financially solvent, solely based on selling stuff to
people on the web. For this reason, there is likely a demand for this type of application, and an interest
in seeing how it’s done.
Second, I think e-commerce is interesting. An e-commerce project using any particular framework
tends to be fairly complex, with lots of ins and outs. They allow you, as a developer, to start by building a
simple product catalog, and then go deeper into hooking into third-party payment processors with web
service calls. If you can get your head around the logic behind our Django e-commerce project, then there’s
probably very little else you won’t be able to figure out how to do with Django. Lastly (and don’t tell anyone
this), I’m pretty bad at visual design. I’m a programmer. Visual design for e-commerce tends to be pretty

straightforward. Generally, you don’t need to create graphics-heavy grunge designs to wow your audience,
like you might need to do for a blog or business-card web site. As far as e-commerce goes: the simpler and
cleaner, the better. I can handle that. However, just because we won’t be focusing on design in this book
doesn’t mean that it’s not an important part of any e-commerce site. Customers and their purchasing
decisions are very much influenced by the look and feel of a web site, so it’s well worth your time to learn a
bit more about design and make sure that your site doesn’t turn customers off visually.
So, let’s get right down to it and figure out what our needs are. Maybe you have some idea of what
you want to build: I do. Before jumping right in and starting with the coding process, I’m going to take a
second to jot down some thoughts about what it is that we’re going to create. It’s common practice for
software developers to write a specification for larger projects before they start coding. There are few
different kinds of specifications; the one that we’re going to do now is a functional specification, which
will describe in plain English what our code is supposed to do.
Specifications vary in style and format. They can be extremely stilted and formal, or they can be
much less formal. They can be bulleted lists of features, descriptive text, or take the form of user stories
that describe the customer experience on the site. How you choose to write your own specification is not

1


CHAPTER 1 ■ BEST LAID PLANS

terribly important, but it is important that you write something, just to make sure that your ducks are in a
row and you don’t run into unforeseen problems with your plans down the line. If you make any
mistakes or run into problems, it’s much easier (and cheaper) to change a few lines of text on paper than
change lots of written code.
I’m going to start by writing a quick, very informal functional specification for our e-commerce
project. Take a moment to do the same, and let’s reconvene back here when you’re finished. Done?
Okay, here’s mine: “Modern Musician will be an online e-commerce catalog that sells instruments, sheet
music, and music accessories to its customers. We’re going to ship orders from the Cleveland, OH
location where our retail shop currently does business.”

Okay, so that’s a little short and doesn’t tell us a whole lot. It doesn’t refine our goals or help us with
our decisions or the overall design process. So, I’m going to have a second and much longer go at it:
“Modern Musician will be an online e-commerce catalog that sells instruments, sheet music, and
music accessories to its customers. When the user first comes to the site, the home page will display
some featured products, a list of categories, and search box that will let them search the catalog.
Navigation will be straight across the top below the banner. Product lists should be thumbnails that
include a small image of the product, with the product name. Products can be in as many categories as
we want. We need to be able to add products and categories through a form so we don’t need to always
have computer programmers doing it. These forms need to be protected so only authorized individuals
can access them. Products can be added to a cart. Checkout will be a single page where we prompt
customers for their information and let them submit the order to us. (How can we inform customers
about our privacy policy? Make it always available to them?) We’re going to ship orders from the
Cleveland, OH location where our retail shop currently does business. Search Engine Optimization
(SEO) should always be a priority. Everything should be stored securely. Our site should be accessible to
people with disabilities, such as blind people. How should we order products when several are listed on
a single page, such as a category page? We need analytics to track conversions and figure out who’s
buying what. The administrative login also needs a place for us to view orders. Orders can only be placed
with a valid credit card on the site, and once the card is approved through a real-time lookup, the order
can be submitted with a status of ”submitted.” Fulfillment will occur on our end, and we’ll set the status
of the order to “processed” once they’ve been shipped. We need to handle returns easily. This will
require the ability to refund a customer’s money, less any handling fees we might charge them. How can
we make this information available to the customer? Where should we explain our return policy, during
checkout? A hyperlink to a “Return Policy” page.”
Okay, so that specification was still pretty short and very informal. That’s okay; the point is not to
convince venture capitalists to fund us, but to figure out what we’re going to do, internally, by getting the
mental juices flowing. It can be free-form. Crawl through the site you’re envisioning in your mind and jot
down any thoughts or questions that come to you. Keep it around and add to it as ideas come to you.
The more ideas you have in mind from the start, before you start building the thing, the less likely you are
to forget something mission-critical and have to go back and redo a bunch of your work.


Selling Stuff Online
I like Shopify. Shopify is an online provider of e-commerce web applications. Sign up with them and
you’ll have your own store up online very quickly. It’s very affordable for small businesses, it’s easy to
use, and the interface is quite slick. You can even set up a store initially for free, and they’ll still
accommodate ten sales transactions on your site per month.
But in this book, I’m going to create an e-commerce application. What we’re going to create in this
book is very similar to Shopify. We’re going to create a product catalog, shopping cart, checkout system,
and allow users to leave product reviews. Why would you want to roll your own solution from scratch
when it’s easy, cheap, and takes so little time to use a provider like Shopify?
The reason has to do with a concept in business referred to as a core competency. Like most terms in
the business world, this refers to a concept that seems drop-dead simple and completely obvious to

2


×