The Django Book

Chapter 1: Introduction to Django

第一章 Django介绍

This book is about Django, a Web development framework that saves you time and makes Web development a joy. Using Django, you can build and maintain high-quality Web applications with minimal fuss.

本书所讲的是Django:一款能够节约你的时间并且让你的开发乐趣横生的web开发框架。使用Django,花极少时间即可构建和维护质量上乘的Web应用。

At its best, Web development is an exciting, creative act; at its worst, it can be a repetitive, frustrating nuisance. Django lets you focus on the fun stuff the crux of your Web application while easing the pain of the repetitive bits. In doing so, it provides high-level abstractions of common Web development patterns, shortcuts for frequent programming tasks, and clear conventions for how to solve problems. At the same time, Django tries to stay out of your way, letting you work outside the scope of the framework as needed.

从好的方面来看,Web 开发激动人心且富于创造性;从另一面来看,它却是份繁琐而令人生厌的工作。通过减少重复的代码,Django 使你能够专注于 web 应用上有 趣的关键性的东西。为了达到这个目标,Django 提供了通用Web开发模式的高度抽象,提供了频繁进行的编程作业的快速解决方法,以及为“如何解决问题”提供了清晰明了的约定。同时,Django 尝试留下一些方法,来让你根据需要在framework之外来开发。

The goal of this book is to make you a Django expert. The focus is twofold. First, we explain, in depth, what Django does and how to build Web applications with it. Second, we discuss higher-level concepts where appropriate, answering the question How can I apply these tools effectively in my own projects? By reading this book, youll learn the skills needed to develop powerful Web sites quickly, with code that is clean and easy to maintain.

本书的目的是将你培养成Django专家。主要侧重于两方面:第一,我们深度解释 Django 到底做了哪些工作以及如何用她构建Web应用;第二,我们将会在适当的地方讨论更高级的概念,并解释如何在自己的项目中高效的使用这些工具。通过阅读此书,你将学会快速开发功能强大网站的技巧,并且你的代码将会十分 清晰,易于维护。

In this chapter, we provide a high-level overview of Django.

在这一章中,我们将一览 Django 的全貌。

What Is a Web Framework?

什么是Web框架?

Django is a prominent member of a new generation of Web frameworks . So what exactly does that term mean?

Django是一个卓越的新一代Web框架,而Django这个词语的意义是什么呢?

To answer that question, lets consider the design of a Web application written using the Common Gateway Interface (CGI) standard, a popular way to write Web applications circa 1998. In those days, when you wrote a CGI application, you did everything yourself the equivalent of baking a cake from scratch. For example, heres a simple CGI script, written in Python, that displays the ten most recently published books from a database:

要回答这个问题,让我们来看看通过编写标准的CGI程序来开发Web应用,这在大约1998年的时候非常流行。编写CGI Web应用时,你需要自己处理所有的操作,就像你想烤面包,但是都需要自己生火一样。下面是实例,一个简单的CGI脚本,用Python写的,读取数据库并显示最新发布的十本书:

#!/usr/bin/python

import MySQLdb

print "Content-Type: text/html"
print
print "<html><head><title>Books</title></head>"
print "<body>"
print "<h1>Books</h1>"
print "<ul>"

connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db')
cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10")
for row in cursor.fetchall():
    print "<li>%s</li>" % row[0]

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

connection.close()

This code is straightforward. First, it prints a Content-Type line, followed by a blank line, as required by CGI. It prints some introductory HTML, connects to a database and executes a query that retrieves the latest ten books. Looping over those books, it generates an HTML unordered list. Finally, it prints the closing HTML and closes the database connection.

代码十分简单。首先,根据CGI的要求输出一行Content-Type,接下来是一个空行。再接下来是一些HTML的起始标签,然后连接数据库并执行一些查询操作,获取最新的十本书。遍历这些书,同时生成一个HTML的无序序列。最后,输出HTML的结束标签并且关闭数据库连接。

With a one-off dynamic page such as this one, the write-it-from-scratch approach isnt necessarily bad. For one thing, this code is simple to comprehend even a novice developer can read these 16 lines of Python and understand all it does, from start to finish. Theres nothing else to learn; no other code to read. Its also simple to deploy: just save this code in a file called latestbooks.cgi , upload that file to a Web server, and visit that page with a browser.

类似这样的一次性动态页面,从头写起并不是最好的办法。其中一点,这些代码简单易懂,就算是一个开发初学者都能理解这16行代码从开始到结束做了些什么,不需要阅读额外的代码。同样这16行代码也很容易部署:只需要将它保存在名为“latestbooks.cgi”的文件里,上传至网络服务器,通过浏览器访问即可。

But as a Web application grows beyond the trivial, this approach breaks down, and you face a number of problems:

但是Web应用远远要复杂很多,这种方法就不再适用,而且你将会要面对很多问题:

  • What happens when multiple pages need to connect to the database? Surely that database-connecting code shouldnt be duplicated in each individual CGI script, so the pragmatic thing to do would be to refactor it into a shared function.

  • 当多个动态页面需要同时连接数据库时,将会发生什么?当然,连接数据库的代码不 应该同时存在于各个独立的CGI脚本中,所以最踏实的做法是把这些代码重新组织到一个公共函数里面。

  • Should a developer really have to worry about printing the Content-Type line and remembering to close the database connection? This sort of boilerplate reduces programmer productivity and introduces opportunities for mistakes. These setup- and teardown-related tasks would best be handled by some common infrastructure.

  • 一个开发人员真的需要去关注如何输出Content-Type以及完成所有操作后去关闭数据库么?此类问题只会降低开发人员的工作效率,增加犯错误的几率。那些初始化和释放相关的工作应该交给一些通用的框架来完成。

  • What happens when this code is reused in multiple environments, each with a separate database and password? At this point, some environment-specific configuration becomes essential.

  • 如果这样的代码被重用到一个复合的环境中会发生什么?每个页面都分别对应独立的数据库和密码吗?从这点看来,就需要一些环境相关的配置文件。

  • What happens when a Web designer who has no experience coding Python wishes to redesign the page? Ideally, the logic of the page the retrieval of books from the database would be separate from the HTML display of the page, so that a designer could edit the latter without affecting the former.

  • 如果一个Web设计师,完全没有Python开发经验,但是又需要重新设计页面的话,又将 发生什么呢?理想的情况是,页面显示的逻辑与从数据库中读取书本记录分隔开,这样 Web设计师的重新设计不会影响到之前的业务逻辑。

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

以上正是Web框架致力于解决的问题。Web框架为应用程序提供了一套程序框架, 这样你可以专注于编写清晰、易维护的代码,而无需从头做起。简单来说,这就是Django所能做的。

The MVC Design Pattern

MVC 设计模式

Lets dive in with a quick example that demonstrates the difference between the previous approach and that undertaken using a Web framework. Heres how you might write the previous CGI code using Django:

让我们来研究一个简单的例子,通过该实例,你可以分辨出,通过Web框架来实现的功能与之前的方式有何不同。下面就是通过使用Django来完成以上功能的例子:

# models.py (the database tables)

from django.db import models

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


# views.py (the business logic)

from django.shortcuts import render_to_response
from models import Book

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


# urls.py (the URL configuration)

from django.conf.urls.defaults import *
import views

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


# latest_books.html (the template)

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

Dont worry about the particulars of how this works just yet we just want you to get a feel for the overall design. The main thing to note here is the separation of concerns :

先不要担心这个东西是 如何 工作的,我们主要是先想让你知道总体的设计,这里关键要注意的是 分离问题

  • The models.py file contains a description of the database table, as a Python class. This is called a model . Using this class, you can create, retrieve, update, and delete records in your database using simple Python code rather than writing repetitive SQL statements.

  • models.py 文件主要用一个 Python 类来描述数据表。称为 模型(model) 。 运用这个类,你可以通过简单的 Python 的代码来创建、检索、更新、删除 数据库中的记录而无需写一条又一条的SQL语句。

  • The views.py file contains the business logic for the page, in the latest_books() function. This function is called a view .

  • view.py 文件的 latest_books() 函数中包含了该页的业务层逻辑。这个函数叫做 视图(view)

  • The urls.py file specifies which view is called for a given URL pattern. In this case, the URL /latest/ will be handled by the latest_books() function.

  • urls.py 指出了什么样的 URL 调用什么的视图,在这个例子中 /latest/ URL 将会调用 latest_books() 这个函数

  • The latest_books.html is an HTML template that describes the design of the page.

  • latest_books.html 是 html 模板,它描述了这个页面的设计是如何的。

Taken together, these pieces loosely follow the Model-View-Controller (MVC) design pattern. Simply put, MVC defines a way of developing software so that the code for defining and accessing data (the model) is separate from request routing logic (the controller), which in turn is separate from the user interface (the view).

这些部分松散的组合在一起就是模型-视图-控制器(MVC)的设计模式。简单的说, MVC 是一种软件开发的方法,它把代码的定义和数据访问的方法(模型)与请求逻辑 (控制器)还有用户接口(视图)分开来。

A key advantage of such an approach is that components are loosely coupled . That is, each distinct piece of a Django-powered Web application has a single key purpose and can be changed independently without affecting the other pieces. For example, a developer can change the URL for a given part of the application without affecting the underlying implementation. A designer can change a pages HTML without having to touch the Python code that renders it. A database administrator can rename a database table and specify the change in a single place, rather than having to search and replace through a dozen files.

这种设计模式关键的优势在于各种组件都是 松散结合 的。这样,每个由 Django驱动 的Web应用都有着明确的目的,并且可独立更改而不影响到其它的部分。比如,开发者 更改一个应用程序中的 URL 而不用影响到这个程序底层的实现。设计师可以改变 HTML 页面 的样式而不用接触 Python 代码。数据库管理员可以重新命名数据表并且只需更改一个地方,无需从一大堆文件中进行查找和替换。

In this book, each component of this stack gets its own chapter. For example, Chapter 3 covers views, Chapter 4 covers templates, and Chapter 5 covers models. Chapter 5 also discusses Djangos MVC philosophies in depth.

本书中,每个组件都有它自己的一个章节。比如,第三章涵盖了视图,第四章是模板, 而第五章是模型。同时第五章也深入讨论了 Django 的 MVC 思想。

Djangos History

django 历史

Before we dive into more code, we should take a moment to explain Djangos history. Its helpful to understand why the framework was created, because a knowledge of the history will put into context why Django works the way it does.

在我们讨论代码之前我们需要先了解一下 Django 的历史。知道了一些历史知识有助于理解为什么 Django 要建立这个框架,因为这些历史有助于理解Django为何会这样运作。

If youve been building Web applications for a while, youre probably familiar with the problems in the CGI example we presented earlier. The classic Web developers path goes something like this:

如果你曾编写过网络应用程序。那么你很有可能熟悉之前我们的 CGI 例子。传统的 网络开发人员的开发流程是这样的:

  1. Write a Web application from scratch.

  1. 从头开始编写网络应用程序。

  1. Write another Web application from scratch.

  1. 从头编写另一个网络应用程序。

  1. Realize the application from step 1 shares much in common with the application from step 2.

  1. 从第一步中总结(找出其中通用的代码),并运用在第二步中。

  1. Refactor the code so that application 1 shares code with application 2.

  1. 重构代码使得能在第 2 个程序中使用第 1 个程序中的通用代码。

  1. Repeat steps 2-4 several times.

  1. 重复 2-4 步骤若干次。

  1. Realize youve invented a framework.

  1. 意识到你发明了一个框架。

This is precisely how Django itself was created!

这就是为什么 Django 创建的原因!

Django grew organically from real-world applications written by a Web development team in Lawrence, Kansas. It was born in the fall of 2003, when the Web programmers at the Lawrence Journal-World newspaper, Adrian Holovaty and Simon Willison, began using Python to build applications. The World Online team, responsible for the production and maintenance of several local news sites, thrived in a development environment dictated by journalism deadlines. For the sites including LJWorld.com, Lawrence.com, and KUsports.com journalists (and management) demanded that features be added and entire applications be built on an intensely fast schedule, often with only days or hours notice. Thus, Adrian and Simon developed a time-saving Web development framework out of necessity it was the only way they could build maintainable applications under the extreme deadlines.

Django 是从真实世界的应用中成长起来的,它是由 堪萨斯(Kansas)州 Lawrence 城中的一个 网络开发小组编写的。它诞生于 2003 年秋天,那时 Lawrence Journal-World 报纸的 程序员 Adrian Holovaty 和 Simon Willison 开始用 Python 来编写程序。 当时他们的 World Online 小组制作并维护当地的几个新闻站点, 并在以新闻界特有的快节奏开发环境中逐渐发展. 这些站点包括有 LJWorld.com、Lawrence.com 和 KUsports.com, 记者(或管理层) 要求增加的特征或整个程序都能在计划时间内快速的被建立,这些时间通常只有几天 或几个小时。因此为了需要,Adrian 和 Simon 开发了一种节省时间的网络程序开发框架, 这是在截止时间前能完成程序的唯一途径。

In summer 2005, after having developed this framework to a point where it was efficiently powering most of World Onlines sites, the World Online team, which now included Jacob Kaplan-Moss, decided to release the framework as open source software. They released it in July 2005 and named it Django, after the jazz guitarist Django Reinhardt.

2005 年的夏天,当这个框架开发完成时,它已经用来制作了很多个 World Online 的站点。 当时 World Online 小组中的 Jacob Kaplan-Moss 决定把这个框架发布为一个开源软件。 他们在 2005 年的 7 月发布并取名为 Django,来源于一个著名的爵士乐吉他演奏家 Django Reinhardt。

Although Django is now an open source project with contributors across the planet, the original World Online developers still provide central guidance for the frameworks growth, and World Online contributes other important aspects such as employee time, marketing materials, and hosting/bandwidth for the frameworks Web site (http://www.djangoproject.com/).

虽然现在 Django 是一个全世界开发者参与的开源项目,但原始的 World Online 开发者们 仍然提供主要的指导来促进这个框架的成长。 World Online 还有其它方面的重要贡献,比如雇员时间、 市场材料以及框架的 Web 网站的主机和带宽(http://www.djangoproject.com/)。

This history is relevant because it helps explain two key matters. The first is Djangos sweet spot. Because Django was born in a news environment, it offers several features (particularly its admin interface, covered in Chapter 6) that are particularly well suited for content sites sites like eBay, craigslist.org, and washingtonpost.com that offer dynamic, database-driven information. (Dont let that turn you off, though although Django is particularly good for developing those sorts of sites, that doesnt preclude it from being an effective tool for building any sort of dynamic Web site. Theres a difference between being particularly effective at something and being ineffective at other things.)

这些历史都是相关联的,因为她们帮助解释了很重要的两点。第一,Django最可爱的地方, 因为Django诞生于一个新闻环境,她提供了很多的功能(特别是她的管理接口,见第6章), 特别适合提供内容的网站,例如eBay, craigslist.org和washingtonpost.com,提供一种 基于数据库的动态网站。(不要看到这就感到沮丧,尽管Django擅长于动态内容管理系统, 但并不表示Django主要的目的就是用来创建动态内容的网站。 某些方面 特别高效 与 其他方面 不高效 是有区别的)

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

第二,Django的起源造就她的开源社区,因为Django来自于真实世界中的代码,而不是 来自于一个科研项目或者商业产品,她主要集中力量来解决Web开发中遇到的问题,同样 也是Django的开发者经常遇到的问题。这样,Django每天在现有的基础上进步。框架的 开发者对于为开发人员节省开发时间具有极大的兴趣,编写更加容易维护的程序,同时 保证程序运行的效率。开发人员自我激励,尽量的节省时间和享受他们的工作(To put it bluntly, they eat their own dog food.)

How to Read This Book

如何阅读本书

In writing this book, we tried to strike a balance between readability and reference, with a bias toward readability. Our goal with this book, as stated earlier, is to make you a Django expert, and we believe the best way to teach is through prose and plenty of examples, rather than a providing an exhaustive but bland catalog of Django features. (As someone once said, you cant expect to teach somebody how to speak merely by teaching them the alphabet.)

在编写本书时,我们努力尝试在可读性和参考性间做一个平衡,当然本书会偏向于可 读性。本书的目标,之前也提过,是要将你培养成一名Django专家,我们相信,最好 的方式就是文章和充足的实例,而不是提供一堆详尽却乏味的关于Django特色的手册。 (曾经有人说过,如果仅仅教字母表是无法教会别人说话的。)

With that in mind, we recommend that you read Chapters 1 through 7 in order. They form the foundation of how to use Django; once youve read them, youll be able to build Django-powered Web sites. The remaining chapters, which focus on specific Django features, can be read in any order.

按照这种思路,我们推荐按顺序阅读第 1-7 章。这些章节构成了如何使用 Django 的基础;读过之后,你就可以搭建由 Django 支撑的网站了。剩下的章节重点讲述 Django 的其它一些特性,可以按照任何顺序阅读。

The appendixes are for reference. They, along with the free documentation at http://www.djangoproject.com/, are probably what youll flip back to occasionally to recall syntax or find quick synopses of what certain parts of Django do.

附录部分用作参考资料。要回忆语法或查阅 Django 某部分的功能概要时,你偶尔可能会回来翻翻这些资料以及 http://www.djangoproject.com/ 上的免费文档。

Required Programming Knowledge

所需编程知识

Readers of this book should understand the basics of procedural and object-oriented programming: control structures (if , while , and for ), data structures (lists, hashes/dictionaries), variables, classes, and objects.

本书读者需要理解基本的面向过程和面向对象编程:流程控制( ifwhilefor ),数据结构(列表,哈希表/字典),变量,类和对象。

Experience in Web development is, as you may expect, very helpful, but its not required to read this book. Throughout the book, we try to promote best practices in Web development for readers who lack this type of experience.

Web开发经验,正如你所想的,也是非常有帮助的,但是对于阅读本书,并不是必须的。 通过本书,我们尽量给缺乏经验的开发人员提供在Web开发中最好的实践。

Required Python Knowledge

所需python知识

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

本质上来说, Django 只不过是用 Python 编写的一组类库。用 Django 开发站点就是使用这些类库编写 Python 代码。因此,学习 Django 的关键就是学习如何进行 Python 编程并理解 Django 类库的运作方式。

If you have experience programming in Python, you should have no trouble diving in. By and large, the Django code doesnt perform black magic (i.e., programming trickery whose implementation is difficult to explain or understand). For you, learning Django will be a matter of learning Djangos conventions and APIs.

如果你有Python开发经验,在学习过程中应该不会有任何问题,基本上,Django的代码并 没有使用一些黑色魔法(例如代码中的欺骗行为,某个实现解释或者理解起来十分困难)。 对你来说,学习Django就是学习她的命名规则和API。

If you dont have experience programming in Python, youre in for a treat. Its easy to learn and a joy to use! Although this book doesnt include a full Python tutorial, it highlights Python features and functionality where appropriate, particularly when code doesnt immediately make sense. Still, we recommend you read the official Python tutorial, available online at http://docs.python.org/tut/. We also recommend Mark Pilgrims free book Dive Into Python , available at http://www.diveintopython.org/ and published in print by Apress.

如果你没有使用 Python 编程的经验,你一定会学到很多东西。它是非常易学易用的。 虽然这本书没有包括一个完整的 Python 教程, 但也算是一个恰当的介绍了 Python特征和 功能的集锦。当然,我们推荐你读一下官方的 Python 教程,它可 以从 http://docs.python.org/tut/ 在线获得。另外我们也推荐 Mark Pilgrims的 书 Dive Into Pythonhttp://www.diveintopython.org/

New Django Features

Django 之新特性

As we noted earlier, Django is frequently improved, and it will likely have a number of useful even essential new features by the time this book is published. Thus, our goal as authors of this book is twofold:

正如我们之前提到的,Django 改进频繁,到本书出版时,可能有一些甚至是 非常基本 的新功能将被推出。因此,作为作者,我们要通过此书达到两个方面的目标:

  • Make sure this book is as future-proof as possible, so that whatever you read here will still be relevant in future Django versions

  • 保证本书尽可能的面向未来,因此,不管你在本书中读到什么内容,在未来新 的Django版本中都将会可用的。

  • Actively update this book on its Web site, http://www.djangobook.com/, so you can access the latest and greatest documentation as soon as we write it

  • 及时的更新本书的在线版, http://www.djangobook.com/ ,这样在我们完成 新的章节后,你可以获得最新和最好的版本。

If you want to implement something with Django that isnt explained in this book, check the latest version of this book on the aforementioned Web site, and also check the official Django documentation.

如果你想用django来实现某些书中没有提到的功能,请到前面提到的网站上检查这本书 的地最新版本,并且同样记得要去检查官方的django文档。

Getting Help

获取帮助

One of the greatest benefits of Django is its kind and helpful user community. For help with any aspect of Django from installation, to application design, to database design, to deployment feel free to ask questions online.

django的最大的益处是,有一群乐于助人的人在django社区上.你可以毫无约束的提各种 问题在上面如:从django的安装,app 设计,db 设计,发布。

  • The Django IRC channel is where Django users hang out to chat and help each other in real time. Join the fun by logging on to #django on the Freenode IRC network.

  • django irc channel如果django用户遇到什么棘手的问题希望的及时地回复是可以使用它。 在freenode IRC network加入#django

Whats Next

下一章

In the next chapter, well get started with Django, covering installation and initial setup.

下一章,主要讲述如何开始安装和初始化django。

Copyright 2006 Adrian Holovaty and Jacob Kaplan-Moss.
This work is licensed under the GNU Free Document License.
Hosting graciously provided by media temple
Chinese translate hosting by py3k.cn. 粤ICP备16122281号-1