You are previewing Python Web Development with Django®.
O'Reilly logo
Python Web Development with Django®

Book Description

Using the simple, robust, Python-based Django framework, you can build powerful Web solutions with remarkably few lines of code. In Python Web Development with Django®, three experienced Django and Python developers cover all the techniques, tools, and concepts you need to make the most of Django 1.0, including all the major features of the new release.

The authors teach Django through in-depth explanations, plus provide extensive sample code supported with images and line-by-line explanations. You’ll discover how Django leverages Python’s development speed and flexibility to help you solve a wide spectrum of Web development problems and learn Django best practices covered nowhere else. You’ll build your first Django application in just minutes and deepen your real-world skills through start-to-finish application projects including

  • Simple Web log (blog)

  • Online photo gallery

  • Simple content management system

  • Ajax-powered live blogger

  • Online source code sharing/syntax highlighting tool

  • How to run your Django applications on the Google App Engine

  • This complete guide starts by introducing Python, Django, and Web development concepts, then dives into the Django framework, providing a deep understanding of its major components (models, views, templates), and how they come together to form complete Web applications. After a discussion of four independent working Django applications, coverage turns to advanced topics, such as caching, extending the template system, syndication, admin customization, and testing. Valuable reference appendices cover using the command-line, installing and configuring Django, development tools, exploring existing Django applications, the Google App Engine, and how to get more involved with the Django community.

    Introduction 1

    Part I: Getting Started

    Chapter 1: Practical Python for Django 7

    Chapter 2: Django for the Impatient: Building a Blog 57

    Chapter 3: Starting Out 77

    Part II: Django in Depth

    Chapter 4: Defining and Using Models 89

    Chapter 5: URLs, HTTP Mechanisms, and Views 117

    Chapter 6: Templates and Form Processing 135

    Part III: Django Applications by Example

    Chapter 7: Photo Gallery 159

    Chapter 8: Content Management System 181

    Chapter 9: Liveblog 205

    Chapter 10: Pastebin 221

    Part IV: Advanced Django Techniques and Features

    Chapter 11: Advanced Django Programming 235

    Chapter 12: Advanced Django Deployment 261

    Part V: Appendices

    Appendix A: Command Line Basics 285

    Appendix B: Installing and Running Django 295

    Appendix C: Tools for Practical Django Development 313

    Appendix D: Finding, Evaluating, and Using Django Applications 321

    Appendix E: Django on the Google App Engine 325

    Appendix F: Getting Involved in the Django Project 337

    Index 339

    Colophon 375

    Table of Contents

    1. Copyright
      1. Dedication
    2. Developer’s Library: Essential References for Programming Professionals
    3. Preface
      1. Welcome to Django!
      2. About This Book
        1. Chapter Guide
          1. Part I, “Getting Started”
          2. Chapter 1, “Practical Python for Django”
          3. Chapter 2, “Django for the Impatient: Building a Blog”
          4. Chapter 3, “Starting Out”
          5. Part II, “Django in Depth”
          6. Chapter 4, “Defining and Using Models”
          7. Chapter 5, “URLs, HTTP Mechanisms, and Views”
          8. Chapter 6, “Templates and Form Processing”
          9. Part III, “Django Applications by Example”
          10. Chapter 7, “Photo Gallery”
          11. Chapter 8, “Content Management System”
          12. Chapter 9, “Liveblog”
          13. Chapter 10, “Pastebin”
          14. Part IV, “Advanced Django Techniques and Features”
          15. Chapter 11, “Advanced Django Programming”
          16. Chapter 12, “Advanced Django Deployment”
          17. Part V, “Appendices”
          18. Appendix A, “Command Line Basics”
          19. Appendix B, “Installing and Running Django”
          20. Appendix C, “Tools for Practical Django Development”
          21. Appendix D, “Finding, Evaluating, and Using Django Applications”
          22. Appendix E, “Django on the Google App Engine”
          23. Appendix F, “Getting Involved in the Django Project”
        2. Conventions
        3. Book Resources
    4. Acknowledgments
    5. About the Authors
    6. Introduction
      1. Where Web Frameworks Come From
      2. A Better Way
      3. We’re Not in Kansas Anymore
      4. Web Development Is Better with Python and Django
    7. I. Getting Started
      1. 1. Practical Python for Django
        1. Python Skills Are Django Skills
        2. Getting Started: Python’s Interactive Interpreter
        3. Python Basics
          1. Comments
          2. Variables and Assignment
          3. Operators
        4. Python Standard Types
          1. Object Boolean Values
          2. Numbers
          3. Numeric Operators
          4. Numeric Built-in and Factory Functions
          5. Sequences and Iterables
            1. Sequence Slicing
            2. Other Sequence Operators
          6. Lists
            1. List Methods
            2. List Comprehensions
            3. Generator Expressions
          7. Strings
            1. String Designators
            2. String Format Operator and Triple Quotes
            3. Tuples
              1. Tuple-Related Gotchas in Django
          8. Sequence Built-ins and Factory Functions
          9. Mapping Type: Dictionaries
            1. Dictionary Operations, Methods, and Mapping Functions
          10. Standard Type Summary
        5. Flow Control
          1. Conditionals
          2. Loops
        6. Exception Handling
          1. The finally Clause
          2. Throwing Exceptions with raise
        7. Files
        8. Functions
          1. Declaring and Calling Functions
            1. Keyword Arguments (in Function Calls)
            2. Default Arguments (in Function Signatures)
          2. Functions Are First-Class Objects
            1. References
          3. Anonymous Functions
            1. Expressions Versus Statements
            2. Using lambda
          4. *args and **kwargs
            1. * and ** in Function Calls
            2. * and ** in Function Signatures
          5. Decorators
        9. Object-Oriented Programming
          1. Class Definitions
          2. Instantiation
          3. Subclassing
          4. Inner Classes
        10. Regular Expressions
          1. The re module
          2. Searching Versus Matching
        11. Common Gotchas
          1. Single-Item Tuples
          2. Modules
            1. Can I Import a Module More Than Once?
            2. Packages
          3. Mutability
            1. How Mutability Affects Method Calls
            2. Copying Objects and Mutability
          4. Constructor Versus Initializer
            1. Dynamic Instance Attributes
        12. Coding Style (PEP 8 and Beyond)
          1. Indent Four Spaces
          2. Use Spaces and Not Tabs
          3. Don’t Write Single-Line Suites on the Same Line as the Header
          4. Create Documentation Strings (aka “docstrings”)
        13. Summary
      2. 2. Django for the Impatient: Building a Blog
        1. Creating the Project
        2. Running the Development Server
        3. Creating the Blog Application
        4. Designing Your Model
        5. Setting Up the Database
          1. Using a Database Server
          2. Using SQLite
          3. Creating the Tables
        6. Setting Up the Automatic admin Application
        7. Trying Out the admin
        8. Making Your Blog’s Public Side
          1. Creating a Template
          2. Creating a View Function
          3. Creating a URL Pattern
        9. Finishing Touches
          1. Template Niceties
          2. Date-Based Ordering
          3. Timestamp Formatting Via a Template Filter
        10. Summary
      3. 3. Starting Out
        1. Dynamic Web Site Basics
          1. Communication: HTTP, URLs, Requests, Responses
          2. Data Storage: SQL and Relational Databases
          3. Presentation: Rendering Templates into HTML and Other Formats
          4. Putting It All Together
        2. Understanding Models, Views, and Templates
          1. Separating the Layers (MVC)
            1. Django’s Approach
          2. Models
          3. Views
          4. Templates
        3. Overall Django Architecture
        4. Core Philosophies of Django
          1. Django Tries to Be Pythonic
          2. Don’t Repeat Yourself (DRY)
          3. Loose Coupling and Flexibility
          4. Rapid Development
        5. Summary
    8. II. Django in Depth
      1. 4. Defining and Using Models
        1. Defining Models
          1. Why Use an ORM?
            1. Encapsulation of Useful Methods
            2. Portability
            3. Safety
            4. Expressiveness
          2. Django’s Rich Field Types
            1. Primary Keys and Uniqueness
          3. Relationships Between Models
            1. Foreign Keys
            2. Many-to-Many Relationships
            3. Composition with One-to-One Relationships
            4. Constraining Relationships
          4. Model Inheritance
            1. Abstract Base Classes
            2. Multi-table Inheritance
          5. Meta Inner Class
          6. Admin Registration and Options
        2. Using Models
          1. Creating and Updating Your Database Using manage.py
          2. Query Syntax
            1. QuerySet as Database Query
            2. QuerySet as Container
            3. QuerySet as Building Block
            4. Sorting Query Results
            5. Other Ways to Alter Queries
            6. Query Keyword Composition with Q and ~Q
            7. Tweaking the SQL with Extra
          3. Utilizing SQL Features Django Doesn’t Provide
            1. Schema Definition and Custom Initial SQL
            2. Fixtures: Loading and Dumping Data
            3. Custom SQL Queries
        3. Summary
      2. 5. URLs, HTTP Mechanisms, and Views
        1. URLs
          1. Introduction to URLconfs
          2. Replacing Tuples with url
          3. Using Multiple patterns Objects
          4. Including Other URL Files with include
          5. Function Objects Versus Function-Name Strings
        2. Modeling HTTP: Requests, Responses, and Middleware
          1. Request Objects
            1. GET and POST Dictionaries
            2. Cookies and Sessions
            3. Other Server Variables
          2. Response Objects
          3. Middleware
            1. Request Middleware
            2. Response Middleware
        3. Views/Logic
          1. Just Python Functions
          2. Generic Views
          3. Semi-generic Views
          4. Custom Views
            1. Framework-Provided Shortcuts
            2. Other Observations
        4. Summary
      3. 6. Templates and Form Processing
        1. Templates
          1. Understanding Contexts
          2. Template Language Syntax
            1. Template Filters
            2. Tags
            3. Blocks and Extends
            4. Including Other Templates
        2. Forms
          1. Defining Forms
            1. Model-Based Forms
            2. Saving ModelForms
            3. Differing from the Model
            4. Form Subclassing
          2. Filling Out Forms
          3. Validation and Cleaning
          4. Form Display
            1. Displaying Forms Wholesale
            2. Displaying Forms Piecemeal
          5. Widgets
            1. Overriding a Field’s Default Widget
        3. Summary
    9. III. Django Applications by Example
      1. 7. Photo Gallery
        1. The Model
        2. Preparing for File Uploads
        3. Installing PIL
        4. Testing ImageField
        5. Building Our Custom File Field
          1. Initialization
          2. Adding Attributes to the Field
          3. Saving and Deleting the Thumbnail
        6. Using ThumbnailImageField
        7. Setting Up DRY URLs
        8. The Item App’s URL Layout
        9. Tying It All Together with Templates
        10. Summary
      2. 8. Content Management System
        1. What’s a CMS?
        2. The Un-CMS: Flatpages
          1. Enabling the Flatpages App
          2. Flatpage Templates
          3. Testing It Out
        3. Beyond Flatpages: A Simple Custom CMS
          1. Making the Model
          2. Imports
          3. Completing the Model
          4. Controlling Which Stories Are Viewed
          5. Working with Markdown
          6. URL Patterns in urls.py
          7. Admin Views
          8. Displaying Content Via Generic Views
          9. Template Layout
          10. Displaying Stories
          11. Adding Search
          12. Managing Users
          13. Supporting Workflow
        4. Possible Enhancements
        5. Summary
      3. 9. Liveblog
        1. What Exactly Is Ajax?
          1. Why Ajax Is Useful
        2. Planning the Application
          1. Choosing an Ajax Library
        3. Laying Out the Application
        4. Putting the Ajax In
          1. The Basics
          2. The “X” in Ajax (Or XML Versus JSON)
          3. Installing the JavaScript Library
          4. Setting Up and Testing jQuery
            1. Embedding JavaScript Actions in Our Template
          5. Creating the View Function
          6. Using the View Function Via JavaScript
        5. Summary
      4. 10. Pastebin
        1. Defining the Model
        2. Creating the Templates
        3. Designing the URLs
        4. Trying It Out
        5. Limiting Number of Recent Pastes Displayed
        6. Syntax Highlighting
        7. Cleanup Via Cron Job
        8. Summary
    10. IV. Advanced Django Techniques and Features
      1. 11. Advanced Django Programming
        1. Customizing the Admin
          1. Changing Layout and Style Using Fieldsets
          2. Extending the Base Templates
          3. Adding New Views
          4. Authentication Decorators
        2. Using Syndication
          1. The Feed Class
          2. Giving the Feed a URL
          3. Doing More with Feeds
        3. Generating Downloadable Files
          1. Nagios Configuration Files
          2. vCard
          3. Comma-Separated Value (CSV)
          4. Charts and Graphs Using PyCha
        4. Enhancing Django’s ORM with Custom Managers
          1. Changing the Default Set of Objects
          2. Adding New Manager Methods
        5. Extending the Template System
          1. Simple Custom Template Tags
          2. Inclusion Tags
          3. Custom Filters
            1. Filters with an Extra Argument
          4. More Complex Custom Template Tags
          5. Alternative Templating
            1. Plain Text
            2. Choosing an Alternative Templating Mechanism
            3. Using Other Template Engines: Mako
        6. Summary
      2. 12. Advanced Django Deployment
        1. Writing Utility Scripts
          1. Cronjobs for Cleanup
          2. Data Import/Export
        2. Customizing the Django Codebase Itself
        3. Caching
          1. A Basic Caching Recipe
            1. Get a Baseline
            2. Add the Middleware
            3. Set the Cache Type
            4. Try It Out
          2. Caching Strategies
            1. Site-wide
            2. The Per-view Cache
            3. Controlling Cache-Related Headers
            4. The Object Cache
            5. The cache Template Tag
          3. Caching Backend Types
            1. File
            2. Database
            3. Memcached
        4. Testing Django Applications
          1. Doctest Basics
          2. Unittest Basics
          3. Running Tests
          4. Testing Models
          5. Testing Your Entire Web App
          6. Testing the Django Codebase Itself
        5. Summary
    11. V. Appendices
      1. A. Command Line Basics
        1. Putting the “Command” in “Command Line”
        2. Options and Arguments
        3. Pipes and Redirection
        4. Environment Variables
        5. The Path
        6. Summary
      2. B. Installing and Running Django
        1. Python
          1. Mac OS X
          2. Unix/Linux
          3. Windows
          4. Updating Your Path
          5. Testing
          6. Optional Add-ons
            1. Easy Install
            2. IPython
        2. Django
          1. Packaged Releases
          2. Development Version
          3. Installation
          4. Testing
        3. Web Server
          1. The Built-In Server: Not for Production
          2. The Standard Approach: Apache and mod_python
            1. Hooking Django into Apache
            2. “Poking a Hole” for Static Media
          3. The Flexible Alternative: WSGI
          4. Another Approach: Flup and FastCGI
        4. SQL Database
          1. SQLite
          2. PostgreSQL
          3. MySQL
          4. Oracle
          5. Other Databases
        5. Summary
      3. C. Tools for Practical Django Development
        1. Version Control
          1. The Trunk and Branches
          2. Merging
          3. Centralized Version Control
            1. Subversion
          4. Decentralized Version Control
            1. Mercurial
            2. Git
          5. Version Control for Your Project
        2. Project Management Software
          1. Trac
        3. Text Editors
          1. Emacs
          2. Vim
          3. TextMate
          4. Eclipse
      4. D. Finding, Evaluating, and Using Django Applications
        1. Where to Look for Applications
        2. How to Evaluate Applications
        3. How to Use Applications
        4. Sharing Your Own Applications
      5. E. Django on the Google App Engine
        1. Why the App Engine Matters
        2. Pure Google App Engine Applications
        3. Limitations of the App Engine Framework
        4. Google App Engine Helper for Django
          1. Getting the SDK and the Helper
          2. More on the Helper
        5. Integrating the App Engine
          1. Copying the App Engine Code to Your Project
          2. Integrating the App Engine Helper
          3. Porting Your Application to App Engine
          4. Taking a Test Drive
          5. Adding Data
        6. Creating a New Django Application That Runs on App Engine
        7. Summary
        8. Online Resources
      6. F. Getting Involved in the Django Project
      7. Colophon