You are previewing The Definitive Guide to Django: Web Development Done Right.
O'Reilly logo
The Definitive Guide to Django: Web Development Done Right

Book Description

Django, the Python-based equivalent to the Ruby on Rails web development framework, is presently one of the hottest topics in web development today. In The Definitive Guide to Django: Web Development Done Right, Adrian Holovaty, one of Django's creators, and Django lead developer Jacob Kaplan-Moss show you how they use this framework to create award-winning web sites. Over the course of three parts, they guide you through the creation of a web application reminiscent of chicagocrime.org.

The first part of the book introduces Django fundamentals like installation and configuration. You'll learn about creating the components that power a Django-driven web site. The second part delves into the more sophisticated features of Django, like outputting non-HTML content (such as RSS feeds and PDFs), plus caching and user management. The third part serves as a detailed reference to Django's many configuration options and commands. The book even includes seven appendixes for looking up configurations options and commands. In all, this book provides the ultimate tutorial and reference to the popular Django framework.

Table of Contents

  1. About the Authors
  2. About the Technical Reviewer
  3. Acknowledgments
  4. Introduction
  5. I. Getting Started
    1. 1. Introduction to Django
      1. What Is a Web Framework?
      2. The MVC Design Pattern
      3. Django's History
      4. How to Read This Book
        1. Required Programming Knowledge
        2. Required Python Knowledge
        3. New Django Features
        4. Getting Help
      5. What's Next?
    2. 2. Getting Started
      1. Installing Python
      2. Installing Django
        1. Installing an Official Release
        2. Installing Django from Subversion
      3. Setting Up a Database
        1. Using Django with PostgreSQL
        2. Using Django with SQLite 3
        3. Using Django with MySQL
        4. Using Django Without a Database
      4. Starting a Project
        1. The Development Server
      5. What's Next?
    3. 3. The Basics of Dynamic Web Pages
      1. Your First View: Dynamic Content
      2. Mapping URLs to Views
      3. How Django Processes a Request
        1. How Django Processes a Request: Complete Details
      4. URLconfs and Loose Coupling
      5. 404 Errors
      6. Your Second View: Dynamic URLs
        1. A Word About Pretty URLs
        2. Wildcard URLpatterns
      7. Django's Pretty Error Pages
      8. What's Next?
    4. 4. The Django Template System
      1. Template System Basics
      2. Using the Template System
        1. Creating Template Objects
        2. Rendering a Template
        3. Multiple Contexts, Same Template
        4. Context Variable Lookup
        5. Playing with Context Objects
      3. Basic Template Tags and Filters
        1. Tags
        2. Filters
      4. Philosophies and Limitations
      5. Using Templates in Views
      6. Template Loading
        1. render_to_response()
        2. The locals() Trick
        3. Subdirectories in get_template()
        4. The include Template Tag
      7. Template Inheritance
      8. What's Next?
    5. 5. Interacting with a Database: Models
      1. The "Dumb" Way to Do Database Queries in Views
      2. The MTV Development Pattern
      3. Configuring the Database
      4. Your First App
      5. Defining Models in Python
      6. Your First Model
      7. Installing the Model
      8. Basic Data Access
      9. Adding Model String Representations
      10. Inserting and Updating Data
      11. Selecting Objects
        1. Filtering Data
        2. Retrieving Single Objects
        3. Ordering Data
        4. Chaining Lookups
        5. Slicing Data
      12. Deleting Objects
      13. Making Changes to a Database Schema
        1. Adding Fields
        2. Removing Fields
        3. Removing Many-to-Many Fields
        4. Removing Models
      14. What's Next?
    6. 6. The Django Administration Site
      1. Activating the Admin Interface
      2. Using the Admin Interface
        1. Users, Groups, and Permissions
      3. Customizing the Admin Interface
      4. Customizing the Admin Interface's Look and Feel
      5. Customizing the Admin Index Page
      6. When and Why to Use the Admin Interface
      7. What's Next?
    7. 7. Form Processing
      1. Search
      2. The "Perfect Form"
      3. Creating a Feedback Form
      4. Processing the Submission
      5. Custom Validation Rules
      6. A Custom Look and Feel
      7. Creating Forms from Models
      8. What's Next?
    8. 8. Advanced Views and URLconfs
      1. URLconf Tricks
        1. Streamlining Function Imports
        2. Using Multiple View Prefixes
        3. Special-Casing URLs in Debug Mode
        4. Using Named Groups
        5. Understanding the Matching/Grouping Algorithm
        6. Passing Extra Options to View Functions
        7. Using Default View Arguments
        8. Special-Casing Views
        9. Capturing Text in URLs
        10. Determining What the URLconf Searches Against
      2. Including Other URLconfs
        1. How Captured Parameters Work with include()
        2. How Extra URLconf Options Work with include()
      3. What's Next?
  6. II. Django's Subframeworks
    1. 9. Generic Views
      1. Using Generic Views
      2. Generic Views of Objects
      3. Extending Generic Views
        1. Making "Friendly" Template Contexts
        2. Adding Extra Context
        3. Viewing Subsets of Objects
        4. Complex Filtering with Wrapper Functions
        5. Performing Extra Work
      4. What's Next?
    2. 10. Extending the Template Engine
      1. Template Language Review
      2. RequestContext and Context Processors
        1. django.core.context_processors.auth
        2. django.core.context_processors.debug
        3. django.core.context_processors.i18n
        4. django.core.context_processors.request
        5. Guidelines for Writing Your Own Context Processors
      3. Inside Template Loading
      4. Extending the Template System
        1. Creating a Template Library
        2. Writing Custom Template Filters
        3. Writing Custom Template Tags
        4. Shortcut for Simple Tags
        5. Inclusion Tags
      5. Writing Custom Template Loaders
      6. Using the Built-in Template Reference
      7. Configuring the Template System in Standalone Mode
      8. What's Next?
    3. 11. Generating Non-HTML Content
      1. The Basics: Views and MIME Types
      2. Producing CSV
      3. Generating PDFs
        1. Installing ReportLab
        2. Writing Your View
        3. Complex PDFs
      4. Other Possibilities
      5. The Syndication Feed Framework
        1. Initialization
        2. A Simple Feed
        3. A More Complex Feed
        4. Specifying the Type of Feed
        5. Enclosures
        6. Language
        7. URLs
        8. Publishing Atom and RSS Feeds in Tandem
      6. The Sitemap Framework
        1. Installation
        2. Initialization
        3. Sitemap Classes
        4. Shortcuts
        5. Creating a Sitemap Index
        6. Pinging Google
      7. What's Next?
    4. 12. Sessions, Users, and Registration
      1. Cookies
        1. Getting and Setting Cookies
        2. The Mixed Blessing of Cookies
      2. Django's Session Framework
        1. Enabling Sessions
        2. Using Sessions in Views
        3. Setting Test Cookies
        4. Using Sessions Outside of Views
        5. When Sessions Are Saved
        6. Browser-Length Sessions vs. Persistent Sessions
        7. Other Session Settings
      3. Users and Authentication
        1. Enabling Authentication Support
        2. Using Users
        3. Logging In and Out
        4. Limiting Access to Logged-in Users
        5. Limiting Access to Users Who Pass a Test
        6. Managing Users, Permissions, and Groups
        7. Using Authentication Data in Templates
      4. The Other Bits: Permissions, Groups, Messages, and Profiles
        1. Permissions
        2. Groups
        3. Messages
        4. Profiles
      5. What's Next?
    5. 13. Caching
      1. Setting Up the Cache
        1. Memcached
        2. Database Caching
        3. Filesystem Caching
        4. Local-Memory Caching
        5. Simple Caching (for Development)
        6. Dummy Caching (for Development)
        7. CACHE_BACKEND Arguments
      2. The Per-Site Cache
      3. The Per-View Cache
        1. Specifying Per-View Cache in the URLconf
      4. The Low-Level Cache API
      5. Upstream Caches
        1. Using Vary Headers
        2. Other Cache Headers
      6. Other Optimizations
      7. Order of MIDDLEWARE_CLASSES
      8. What's Next?
    6. 14. Other Contributed Subframeworks
      1. The Django Standard Library
      2. Sites
        1. Scenario 1: Reusing Data on Multiple Sites
        2. Scenario 2: Storing Your Site Name/Domain in One Place
        3. How to Use the Sites Framework
        4. The Sites Framework's Capabilities
        5. CurrentSiteManager
        6. How Django Uses the Sites Framework
      3. Flatpages
        1. Using Flatpages
        2. Adding, Changing, and Deleting Flatpages
        3. Using Flatpage Templates
      4. Redirects
        1. Using the Redirects Framework
        2. Adding, Changing, and Deleting Redirects
      5. CSRF Protection
        1. A Simple CSRF Example
        2. A More Complex CSRF Example
        3. Preventing CSRF
      6. Form Tools
        1. django.contrib.formtools.preview
        2. Using FormPreview
      7. Humanizing Data
        1. apnumber
        2. intcomma
        3. intword
        4. ordinal
      8. Markup Filters
      9. What's Next?
    7. 15. Middleware
      1. What's Middleware?
      2. Middleware Installation
      3. Middleware Methods
        1. Initializer: __init__(self)
        2. Request Preprocessor: process_request(self, request)
        3. View Preprocessor: process_view (self, request, view, args, kwargs)
        4. Response Postprocessor: process_response(self, request, response)
        5. Exception Postprocessor: process_exception(self, request, exception)
      4. Built-in Middleware
        1. Authentication Support Middleware
        2. "Common" Middleware
        3. Compression Middleware
        4. Conditional GET Middleware
        5. Reverse Proxy Support (X-Forwarded-For Middleware)
        6. Session Support Middleware
        7. Sitewide Cache Middleware
        8. Transaction Middleware
        9. "X-View" Middleware
      5. What's Next?
    8. 16. Integrating with Legacy Databases and Applications
      1. Integrating with a Legacy Database
        1. Using inspectdb
        2. Cleaning Up Generated Models
      2. Integrating with an Authentication System
        1. Specifying Authentication Back-Ends
        2. Writing an Authentication Back-End
      3. Integrating with Legacy Web Applications
      4. What's Next?
    9. 17. Extending Django's Admin Interface
      1. The Zen of Admin
        1. "Trusted users . . ."
        2. ". . . editing . . ."
        3. ". . . structured content"
        4. Full Stop
      2. Customizing Admin Templates
        1. Custom Model Templates
        2. Custom JavaScript
      3. Creating Custom Admin Views
      4. Overriding Built-in Views
      5. What's Next?
    10. 18. Internationalization
      1. Specifying Translation Strings in Python Code
        1. Standard Translation Functions
        2. Marking Strings As No-op
        3. Lazy Translation
        4. Pluralization
      2. Specifying Translation Strings in Template Code
      3. Creating Language Files
        1. Creating Message Files
        2. Compiling Message Files
      4. How Django Discovers Language Preference
      5. The set_language Redirect View
      6. Using Translations in Your Own Projects
      7. Translations and JavaScript
        1. The javascript_catalog View
        2. Using the JavaScript Translation Catalog
        3. Creating JavaScript Translation Catalogs
      8. Notes for Users Familiar with gettext
      9. What's Next?
    11. 19. Security
      1. The Theme of Web Security
      2. SQL Injection
        1. The Solution
      3. Cross-Site Scripting
        1. The Solution
      4. Cross-Site Request Forgery
      5. Session Forging/Hijacking
        1. The Solution
      6. Email Header Injection
        1. The Solution
      7. Directory Traversal
        1. The Solution
      8. Exposed Error Messages
        1. The Solution
      9. A Final Word on Security
      10. What's Next?
    12. 20. Deploying Django
      1. Shared Nothing
      2. A Note on Personal Preferences
      3. Using Django with Apache and mod_python
        1. Basic Configuration
        2. Running Multiple Django Installations on the Same Apache Instance
        3. Running a Development Server with mod_python
        4. Serving Django and Media Files from the Same Apache Instance
        5. Error Handling
        6. Handling a Segmentation Fault
      4. Using Django with FastCGI
        1. FastCGI Overview
        2. Running Your FastCGI Server
        3. Using Django with Apache and FastCGI
        4. FastCGI and lighttpd
        5. Running Django on a Shared-Hosting Provider with Apache
      5. Scaling
        1. Running on a Single Server
        2. Separating Out the Database Server
        3. Running a Separate Media Server
        4. Implementing Load Balancing and Redundancy
        5. Going Big
      6. Performance Tuning
        1. There's No Such Thing As Too Much RAM
        2. Turn Off Keep-Alive
        3. Use Memcached
        4. Use Memcached Often
        5. Join the Conversation
      7. What's Next?
  7. III. Appendixes
    1. A. Case Studies
      1. Cast of Characters
      2. Why Django?
      3. Getting Started
      4. Porting Existing Code
      5. How Did It Go?
      6. Team Structure
      7. Deployment
    2. B. Model Definition Reference
      1. Fields
        1. Field Name Restrictions
        2. AutoField
        3. BooleanField
        4. CharField
        5. CommaSeparatedIntegerField
        6. DateField
        7. DateTimeField
        8. EmailField
        9. FileField
        10. FilePathField
        11. FloatField
        12. ImageField
        13. IntegerField
        14. IPAddressField
        15. NullBooleanField
        16. PhoneNumberField
        17. PositiveIntegerField
        18. PositiveSmallIntegerField
        19. SlugField
        20. SmallIntegerField
        21. TextField
        22. TimeField
        23. URLField
        24. USStateField
        25. XMLField
      2. Universal Field Options
        1. null
        2. blank
        3. choices
        4. db_column
        5. db_index
        6. default
        7. editable
        8. help_text
        9. primary_key
        10. radio_admin
        11. unique
        12. unique_for_date
        13. unique_for_month
        14. unique_for_year
        15. verbose_name
      3. Relationships
        1. Many-to-One Relationships
        2. Many-to-Many Relationships
      4. Model Metadata Options
        1. db_table
        2. db_tablespace
        3. get_latest_by
        4. order_with_respect_to
        5. ordering
        6. permissions
        7. unique_together
        8. verbose_name
        9. verbose_name_plural
      5. Managers
        1. Manager Names
        2. Custom Managers
      6. Model Methods
        1. __str__
        2. get_absolute_url
        3. Executing Custom SQL
        4. Overriding Default Model Methods
      7. Admin Options
        1. date_hierarchy
        2. fields
        3. js
        4. list_display
        5. list_display_links
        6. list_filter
        7. list_per_page
        8. list_select_related
        9. ordering
        10. save_as
        11. save_on_top
        12. search_fields
    3. C. Database API Reference
      1. Creating Objects
        1. What Happens When You Save?
        2. Autoincrementing Primary Keys
      2. Saving Changes to Objects
      3. Retrieving Objects
      4. Caching and QuerySets
      5. Filtering Objects
        1. Chaining Filters
        2. Limiting QuerySets
        3. Query Methods That Return New QuerySets
        4. QuerySet Methods That Do Not Return QuerySets
      6. Field Lookups
        1. exact
        2. iexact
        3. contains
        4. icontains
        5. gt, gte, lt, and lte
        6. in
        7. startswith
        8. istartswith
        9. endswith and iendswith
        10. range
        11. year, month, and day
        12. isnull
        13. search
        14. The pk Lookup Shortcut
      7. Complex Lookups with Q Objects
      8. Related Objects
        1. Lookups That Span Relationships
        2. Foreign Key Relationships
        3. "Reverse" Foreign Key Relationships
        4. Many-to-Many Relationships
        5. Queries over Related Objects
      9. Deleting Objects
      10. Extra Instance Methods
        1. get_FOO_display()
        2. get_next_by_FOO(**kwargs) and get_previous_by_FOO(**kwargs)
        3. get_FOO_filename()
        4. get_FOO_url()
        5. get_FOO_size()
        6. save_FOO_file(filename, raw_contents)
        7. get_FOO_height() and get_FOO_width()
      11. Shortcuts
        1. get_object_or_404()
        2. get_list_or_404()
      12. Falling Back to Raw SQL
    4. D. Generic View Reference
      1. Common Arguments to Generic Views
      2. "Simple" Generic Views
        1. Rendering a Template
        2. Redirecting to Another URL
      3. List/Detail Generic Views
        1. Lists of Objects
        2. Detail Views
      4. Date-Based Generic Views
        1. Archive Index
        2. Year Archives
        3. Month Archives
        4. Week Archives
        5. Day Archives
        6. Archive for Today
        7. Date-Based Detail Pages
      5. Create/Update/Delete Generic Views
        1. Create Object View
        2. Update Object View
        3. Delete Object View
    5. E. Settings
      1. What's a Settings File?
        1. Default Settings
        2. Seeing Which Settings You've Changed
        3. Using Settings in Python Code
        4. Altering Settings at Runtime
        5. Security
        6. Creating Your Own Settings
      2. Designating the Settings: DJANGO_SETTINGS_MODULE
        1. The django-admin.py Utility
        2. On the Server (mod_python)
      3. Using Settings Without Setting DJANGO_SETTINGS_MODULE
        1. Custom Default Settings
        2. Either configure() or DJANGO_SETTINGS_MODULE Is Required
      4. Available Settings
        1. ABSOLUTE_URL_OVERRIDES
        2. ADMIN_FOR
        3. ADMIN_MEDIA_PREFIX
        4. ADMINS
        5. ALLOWED_INCLUDE_ROOTS
        6. APPEND_SLASH
        7. CACHE_BACKEND
        8. CACHE_MIDDLEWARE_KEY_PREFIX
        9. DATABASE_ENGINE
        10. DATABASE_HOST
        11. DATABASE_NAME
        12. DATABASE_OPTIONS
        13. DATABASE_PASSWORD
        14. DATABASE_PORT
        15. DATABASE_USER
        16. DATE_FORMAT
        17. DATETIME_FORMAT
        18. DEBUG
        19. DEFAULT_CHARSET
        20. DEFAULT_CONTENT_TYPE
        21. DEFAULT_FROM_EMAIL
        22. DISALLOWED_USER_AGENTS
        23. EMAIL_HOST
        24. EMAIL_HOST_PASSWORD
        25. EMAIL_HOST_USER
        26. EMAIL_PORT
        27. EMAIL_SUBJECT_PREFIX
        28. FIXTURE_DIRS
        29. IGNORABLE_404_ENDS
        30. IGNORABLE_404_STARTS
        31. INSTALLED_APPS
        32. INTERNAL_IPS
        33. JING_PATH
        34. LANGUAGE_CODE
        35. LANGUAGES
        36. MANAGERS
        37. MEDIA_ROOT
        38. MEDIA_URL
        39. MIDDLEWARE_CLASSES
        40. MONTH_DAY_FORMAT
        41. PREPEND_WWW
        42. PROFANITIES_LIST
        43. ROOT_URLCONF
        44. SECRET_KEY
        45. SEND_BROKEN_LINK_EMAILS
        46. SERIALIZATION_MODULES
        47. SERVER_EMAIL
        48. SESSION_COOKIE_AGE
        49. SESSION_COOKIE_DOMAIN
        50. SESSION_COOKIE_NAME
        51. SESSION_COOKIE_SECURE
        52. SESSION_EXPIRE_AT_BROWSER_CLOSE
        53. SESSION_SAVE_EVERY_REQUEST
        54. SITE_ID
        55. TEMPLATE_CONTEXT_PROCESSORS
        56. TEMPLATE_DEBUG
        57. TEMPLATE_DIRS
        58. TEMPLATE_LOADERS
        59. TEMPLATE_STRING_IF_INVALID
        60. TEST_RUNNER
        61. TEST_DATABASE_NAME
        62. TIME_FORMAT
        63. TIME_ZONE
        64. URL_VALIDATOR_USER_AGENT
        65. USE_ETAGS
        66. USE_I18N
        67. YEAR_MONTH_FORMAT
    6. F. Built-in Template Tags and Filters
      1. Built-in Tag Reference
        1. block
        2. comment
        3. cycle
        4. debug
        5. extends
        6. filter
        7. firstof
        8. for
        9. if
        10. ifchanged
        11. ifequal
        12. ifnotequal
        13. include
        14. load
        15. now
        16. regroup
        17. spaceless
        18. ssi
        19. templatetag
        20. url
        21. widthratio
      2. Built-in Filter Reference
        1. add
        2. addslashes
        3. capfirst
        4. center
        5. cut
        6. date
        7. default
        8. default_if_none
        9. dictsort
        10. dictsortreversed
        11. divisibleby
        12. escape
        13. filesizeformat
        14. first
        15. fix_ampersands
        16. floatformat
        17. get_digit
        18. join
        19. length
        20. length_is
        21. linebreaks
        22. linebreaksbr
        23. linenumbers
        24. ljust
        25. lower
        26. make_list
        27. phone2numeric
        28. pluralize
        29. pprint
        30. random
        31. removetags
        32. rjust
        33. slice
        34. slugify
        35. stringformat
        36. striptags
        37. time
        38. timesince
        39. timeuntil
        40. title
        41. truncatewords
        42. truncatewords_html
        43. unordered_list
        44. upper
        45. urlencode
        46. urlize
        47. urlizetrunc
        48. wordcount
        49. wordwrap
        50. yesno
    7. G. The django-admin Utility
      1. Usage
      2. Available Actions
        1. adminindex [appname appname ...]
        2. createcachetable [tablename]
        3. dbshell
        4. diffsettings
        5. dumpdata [appname appname . . .]
        6. flush
        7. inspectdb
        8. loaddata [fixture fixture . . .]
        9. reset [appname appname . . .]
        10. runfcgi [option]
        11. runserver [optional port number, or ipaddr:port]
        12. shell
        13. sql [appname appname . . .]
        14. sqlall [appname appname . . .]
        15. sqlclear [appname appname . . .]
        16. sqlcustom [appname appname . . .]
        17. sqlindexes [appname appname . . .]
        18. sqlreset [appname appname . . .]
        19. sqlsequencereset [appname appname . . .]
        20. startapp [appname]
        21. startproject [projectname]
        22. syncdb
        23. test
        24. validate
      3. Available Option
        1. --settings
        2. --pythonpath
        3. --format
        4. --help
        5. --indent
        6. --noinput
        7. --noreload
        8. --version
        9. --verbosity
        10. --adminmedia
    8. H. Request and Response Objects
      1. HttpRequest
        1. QueryDict Objects
        2. A Complete Example
      2. HttpResponse
        1. Construction HttpResponses
        2. Setting Headers
        3. HttpResponse Subclasses
        4. Returning Errors
        5. Customizing the 404 (Page Not Found) View
        6. Customizing the 500 (Server Error) View