The Django Book

Chapter 2: Getting Started

第二章 入门

We think its best to get a running start. The details and extent of the Django framework will be fleshed out in the later chapters, but for now, trust us, this chapter will be fun.

良好的开端胜过一切。后续章节将充斥着 Django 框架的细节和拓展,不过现在呢,请相信我们,这一章还是蛮有意思的。

Installing Django is easy. Because Django runs anywhere Python does, Django can be configured in many ways. We cover the common scenarios for Django installations in this chapter. Chapter 20 covers deploying Django to production.

Django 安装很简单。因为所有 Python 可运行的地方 Django 都可以运行,所以可以通过多种方式配置 Django 。这一章中,我们将介绍一些常见的 Django 安装方案。第20章中将介绍如何将 Django 部署为产品。

Installing Python

Python 安装

Django is written in 100% pure Python code, so youll need to install Python on your system. Django requires Python 2.3 or higher.

Django 由百分百的纯 Python 代码编写而成,因此必须在系统中安装 Python 。Django 需要 2.3 或更高版本的 Python。

If youre on Linux or Mac OS X, you probably already have Python installed. Type python at a command prompt (or in Terminal, in OS X). If you see something like this, then Python is installed:

如果使用的是 Linux 或 Mac OS X ,系统可能已经预装了 Python 。在命令提示符下 (或 OS X 的终端中) 输入 python ,如果看到如下信息,说明 Python 已经装好了:

Python 2.4.1 (#2, Mar 31 2005, 00:05:10)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Otherwise, if you see an error such as "command not found" , youll have to download and install Python. See http://www.python.org/download/ to get started. The installation is fast and easy.

不然,如果看见类似 "command not found" 的错误,你就不得不下载安装 Python 了。参阅 http://www.python.org/download/ 获取相关入门知识。 Python 的安装 简单而快捷。

Installing Django

Django 安装

In this section, we cover two installation options: installing an official release and installing from Subversion.

本节中,我们介绍两种安装方式:官方发布版安装和通过 Subversion 安装。

Installing an Official Release

官方发布版安装

Most people will want to install the latest official release from http://www.djangoproject.com/download/. Django uses the standard Python distutils installation method, which in Linux land looks like this:

大多数人会考虑从 http://www.djangoproject.com/download/ 下载安装最新的官方发布版。Django 使用了 Python 标准的 distutils 安装法,在 Linux 平台可能包括如下步骤:

  1. Download the tarball, which will be named something like Django-0.96.tar.gz .

  1. 下载 tar 安装包,其文件名可能会是 Django-0.96.tar.gz

  1. tar xzvf Django-*.tar.gz .

  1. tar xzvf Django-*.tar.gz

  1. cd Django-* .

  1. cd Django-*

  1. sudo python setup.py install .

  1. sudo python setup.py install

On Windows, we recommend using 7-Zip to handle all manner of compressed files, including .tar.gz . You can download 7-Zip from http://www.djangoproject.com/r/7zip/.

在windows平台下,我们建议使用 7-Zip 来处理各种格式的压缩文档,包括 “.tar.gz” 格式。7-Zip 可以从 http://www.djangoproject.com/r/7zip/ 下载得到 。

Change into some other directory and start python . If everything worked, you should be able to import the module django :

切换到另一个目录并启动 python 。如果一切就绪,你就可以导入 django 模块了:

>>> import django
>>> django.VERSION
(0, 96, None)

Note

注意

The Python interactive interpreter is a command-line program that lets you write a Python program interactively. To start it, just run the command python at the command line. Throughout this book, we feature example Python code thats printed as if its being entered in the interactive interpreter. The triple greater-than signs (>>> ) signify a Python prompt.

Python 交互解释器是命令行窗口的程序,通过它可以交互式编写 Python 程序。 要启动它只需运行 python 命令。本书所有的 Python 示例代码均以在交互解释器中输入的方式展示。那三个大于号( >>> )是 Python 的提示符。

Installing Django from Subversion

通过 subversion 安装 Django

If you want to work on the bleeding edge, or if you want to contribute code to Django itself, you should install Django from its Subversion repository.

如果想体验有一定风险的新特性,或者想为 Django 贡献代码的话,应该从Subverion 仓库下载安装 Django。

Subversion is a free, open source revision-control system similar to CVS, and the Django team uses it to manage changes to the Django codebase. You can use a Subversion client to grab the very latest Django source code and, at any given time, you can update your local version of the Django code, known as your local checkout , to get the latest changes and improvements made by Django developers.

Subversion 是一种与 CVS 类似的免费开源版本控制系统,Django 开发团队使用它管理 Django 代码库的更新。你可以使用 Subversion 客户端获取最新的 Django 源代码,并可任何时候使用 local checkout 更新本地 Django 代码的版本,以获取 Django 开发者所做的最近更新和改进。

The latest and greatest Django development code is referred to as the trunk . The Django team runs production sites on trunk and strives to keep it stable.

最新和最好的Django代码通常叫做*trunk(主干)*。Django开发团队就是使用trunk代码来运行产品级站点,并全力确保其稳定性。

To grab the latest Django trunk, follow these steps:

遵循以下步骤以获取最新的 Django 主流代码:

  1. Make sure you have a Subversion client installed. You can get the software free from http://subversion.tigris.org/, and you can find excellent documentation at http://svnbook.red-bean.com/.

  1. 确保安装了 Subversion 客户端。可以从 http://subversion.tigris.org/ 免费下载该软件,并从 http://svnbook.red-bean.com/ 获取出色的文档。

  1. Check out the trunk using the command svn co http://code.djangoproject.com/svn/django/trunk djtrunk .

  1. 使用 svn co http://code.djangoproject.com/svn/django/trunk djtrunk 命令检出主流代码。

  1. Create site-packages/django.pth and add the djtrunk directory to it, or update your PYTHONPATH to point to djtrunk .

  1. 创建 site-packages/django.pth 并将 djtrunk 目录添加进去,或者更新 PYTHONPATH 设置,将其指向 djtrunk

  1. Place djtrunk/django/bin on your system PATH. This directory includes management utilities such as django-admin.py .

  1. djtrunk/django/bin 加入系统变量 PATH 中。该目录中包含一些像 django-admin.py 之类的管理工具。

Tip:

提示:

If .pth files are new to you, you can learn more about them at http://www.djangoproject.com/r/python/site-module/.

如果之前没有接触过 .pth 文件,你可以从 http://www.djangoproject.com/r/python/site-module/ 中获取更多相关知识。

After downloading from Subversion and following the preceding steps, theres no need to python setup.py install youve just done the work by hand!

从 Subversion 完成下载并执行了前述步骤后,就没有必要再执行 python setup.py install 了,你刚才已经手动完成了安装!

Because the Django trunk changes often with bug fixes and feature additions, youll probably want to update it every once in a while or hourly, if youre really obsessed. To update the code, just run the command svn update from within the djtrunk directory. When you run that command, Subversion will contact `http://code.djangoproject.com`_, determine if any code has changed, and update your local version of the code with any changes that have been made since you last updated. Its quite slick.

由于 Django 主干代码的更新经常包括 bug 修正和特性添加,如果真的着迷的话,你可能每隔一小段时间就想更新一次。在 djtrunk 目录下运行 svn update 命令即可进行更新。当你使用这个命令时,Subversion 会联络 http://code.djangoproject.com ,判断代码是否有更新,然后把上次更新以来的所有变动应用到本地代码。就这么简单。

Setting Up a Database

安装数据库

Djangos only prerequisite is a working installation of Python. However, this book focuses on one of Djangos sweet spots, which is developing database-backed Web sites, so youll need to install a database server of some sort, for storing your data.

使用 Django 的唯一先决条件是安装 Python。然而,本书所关注的是 Django 的亮点之一——基于数据库的网站开发,因此你必须安装某种类型的数据库来存储数据。

If you just want to get started playing with Django, skip ahead to the Starting a Project sectionbut trust us, youll want to install a database eventually. All of the examples in the book assume you have a database set up.

如果只是想开始摆弄 Django ,可以跳到《开始一个项目》小节。但请相信我们,到最后你还是会想要安装一个数据库。本书中所有例子都假定你安装了一个数据库系统。

As of the time of this writing, Django supports three database engines:

本书写作时,Django 支持 3 种数据库引擎:

Work is in progress to support Microsoft SQL Server and Oracle. The Django Web site will always have the latest information about supported databases.

有人正在努力让它能够支持 SQL Server 和 Oracle 。Django 官方网站会经常发布所支持数据库的最新消息。

Were quite fond of PostgreSQL ourselves, for reasons outside the scope of this book, so we mention it first. However, all the engines listed here will work equally well with Django.

出于本书所讨论范围之外的原因,我们非常偏爱 PostgreSQL,因此我们将第一个提到它。当然,这里所列出的引擎和 Django 都配合得一样好。

SQLite deserves special notice as a development tool. Its an extremely simple in-process database engine that doesnt require any sort of server setup or configuration. Its by far the easiest to set up if you just want to play around with Django, and its even included in the standard library of Python 2.5.

作为开发工具,SQLite 特别值得注意。它是一种非常简单的进程级数据库引擎,无需任何服务器安装或配置工作。如果你只是想摆弄一下 Django ,它是到目前为止最容易安装的,甚至已经被包括在 Python 2.5 的标准类库之中。

On Windows, obtaining database driver binaries is sometimes an involved process. Since youre just getting started with Django, we recommend using Python 2.5 and its built-in support for SQLite. Compiling driver binaries is a downer.

在 Windows 平台上,获取数据库二进制驱动是件很棘手的工作。因为你刚开始接触 Django,我们推荐使用 Python 2.5 及其对 SQLite 的内建支持。编译二进制驱动是件令人沮丧的事。

Using Django with PostgreSQL

在 Django 中使用 PostgreSQL

If youre using PostgreSQL, youll need the psycopg package available from http://www.djangoproject.com/r/python-pgsql/. Take note of whether youre using version 1 or 2; youll need this information later.

使用 PostgreSQL 的话,你需要从 http://www.djangoproject.com/r/python-pgsql/ 下载 psycopg 这个开发包。留意你所用的是 版本 1 还是 2,稍后你会需要这项信息。

If youre using PostgreSQL on Windows, you can find precompiled binaries of psycopg at http://www.djangoproject.com/r/python-pgsql/windows/.

如果在 Windows 平台上使用 PostgreSQL,可以从 http://www.djangoproject.com/r/python-pgsql/windows/ 获取预编译的 psycopg 开发包的二进制文件。

Using Django with SQLite 3

在 Django 中使用 SQLite 3

If youre using a Python version over 2.5, you already have SQLite. If youre working with Python 2.4 or older, youll need SQLite 3 not version 2from http://www.djangoproject.com/r/sqlite/ and the pysqlite package from http://www.djangoproject.com/r/python-sqlite/. Make sure you have pysqlite version 2.0.3 or higher.

如果使用 2.5 及更高版本的 Python ,你无需再安装 SQLite 。但如果使用的是 2.4 或者更低版本的 Python,你所需要的 SQLite 3 不是从 http://www.djangoproject.com/r/sqlite/ 下载到的版本 2 以及从 http://www.djangoproject.com/r/python-sqlite/ 下载 pysqlite 。必须确保使用的是 2.0.3 或者更高版本的 pysqlite

On Windows, you can skip installing the separate SQLite binaries, since theyre statically linked into the pysqlite binaries.

在 Windows 平台上,可以跳过单独的 SQLite 二进制包安装工作,因为它们已被静态链接到 pysqlite 二进制开发包中。

Using Django with MySQL

在 Django 中使用 MySQL

Django requires MySQL 4.0 or above; the 3.x versions dont support nested subqueries and some other fairly standard SQL statements. Youll also need the MySQLdb package from http://www.djangoproject.com/r/python-mysql/.

Django 需要 4.0 或者更高版本的 MySQL,3.x 版不支持嵌套子查询以及其它一些相当标准的 SQL 语句。你还需要从 http://www.djangoproject.com/r/python-mysql/ 下载安装 MySQLdb

Using Django Without a Database

使用无数据库支持的 Django

As mentioned earlier, Django doesnt actually require a database. If you just want to use it to serve dynamic pages that dont hit a database, thats perfectly fine.

正如之前提及过的,Django 并不是非得要数据库才可以运行。如果只用它提供一些不涉及数据库的动态页面服务,也同样可以完美运行。

With that said, bear in mind that some of the extra tools bundled with Django do require a database, so if you choose not to use a database, youll miss out on those features. (We highlight these features throughout this book.)

尽管如此,还是要记住:Django 所捆绑的一些附加工具 一定 需要数据库,因此如果选择不使用数据库,你将不能使用这些功能。 (我们会在全书中标出这些功能。)

Starting a Project

开始一个项目

A project is a collection of settings for an instance of Django, including database configuration, Django-specific options, and application-specific settings.

项目 是 Django 实例一系列设置的集合,它包括数据库配置、Django 特定选项以及应用程序的特定设置。

If this is your first time using Django, youll have to take care of some initial setup. Create a new directory to start working in, perhaps something like /home/username/djcode/ , and change into that directory.

如果第一次使用 Django,必须进行一些初始化设置工作。新建一个工作目录,例如 /home/username/djcode/ ,然后进入该目录。

Note

备忘

django-admin.py should be on your system path if you installed Django via its setup.py utility. If you checked out from Subversion, you can find it in djtrunk/django/bin . Since youll be using django-admin.py often, consider adding it to your path. On Unix, you can do so by symlinking from /usr/local/bin , using a command such as sudo ln -s /path/to/django/bin/django-admin.py /usr/local/bin/django-admin.py . On Windows, youll need to update your PATH environment variable.

如果用的是 setup.py 工具进行的 Django 安装, django-admin.py 应该已被加入了系统路径中。如果是从 Subversion 检出的代码,则可以在 djtrunk/django/bin 中找到它。因为会经常用到 django-admin.py ,可以考虑把它加入系统搜索路径。在 Unix 上,你可以用 sudo ln -s /path/to/django/bin/django-admin.py /usr/local/bin/django-admin.py 这样的命令从 /usr/local/bin 中建立符号连接。在 Windows 平台上则需要更新 PATH 环境变量。

Run the command django-admin.py startproject mysite to create a mysite directory in your current directory.

运行 django-admin.py startproject mysite 命令在当前目录创建一个 mysite 目录。

Lets look at what startproject created:

让我们看看 startproject 都创建了哪些内容:

mysite/
    __init__.py
    manage.py
    settings.py
    urls.py

These files are as follows:

包括下列这些文件:

  • __init__.py : A file required for Python treat the directory as a package (i.e., a group of modules)

  • __init__.py :让 Python 把该目录当成一个开发包 (即一组模块)所需的文件。

  • manage.py : A command-line utility that lets you interact with this Django project in various ways

  • manage.py :一种命令行工具,可让你以多种方式与该 Django 项目进行交互。

  • settings.py : Settings/configuration for this Django project

  • settings.py :该 Django 项目的设置或配置。

  • urls.py : The URL declarations for this Django project; a table of contents of your Django-powered site

  • urls.py :该 Django 项目的 URL 声明,即 Django 所支撑站点的内容列表

Where Should This Directory Live?

这个目录应该放哪儿?

If your background is in PHP, youre probably used to putting code under the Web servers document root (in a place such as /var/www ). With Django, you dont do that. Its not a good idea to put any of this Python code within your Web servers document root, because in doing so you risk the possibility that people will be able to view your code over the Web. Thats not good for security.

有过 PHP 编程背景的话,你可能习惯于将代码都放在 Web 服务器的文档根目录 (例如 /var/www 这样的地方)。而在 Django 中,你不能这样做。把任何 Python 代码放到 Web 服务器的文档根目录中都不是个好主意,因为这样一来,你就要冒着别人透过页面直接看到代码的风险。这对于安全可不是件好事。

Put your code in some directory outside of the document root.

把代码放置在文档根目录 之外 的某些目录中。

The Development Server

开发服务器

Django includes a built-in, lightweight Web server you can use while developing your site. Weve included this server so you can develop your site rapidly, without having to deal with configuring your production Web server (e.g., Apache) until youre ready for production. This development server watches your code for changes and automatically reloads, helping you make many rapid changes to your project without needing to restart anything.

Django 带有一个内建的轻量级 Web 服务器,可供站点开发过程中使用。我们提供这个服务器是为了让你快速开发站点,也就是说在准备发布产品之前,无需进行产品级 Web 服务器(比如 Apache)的配置工作。该开发服务器会监测代码变动并将其自动重载,这样一来,你可快速进行项目修改而无需作任何重启。

Change into the mysite directory, if you havent already, and run the command python manage.py runserver . Youll see something like this:

如果还没有进入 mysite 目录的话,现在进入其中,并运行 python manage.py runserver 命令。你将看到如下输出:

Validating models...
0 errors found.

Django version 1.0, using settings 'mysite.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Although the development server is extremely nice for, well, development, resist the temptation to use this server in anything resembling a production environment. The development server can handle only a single request at a time reliably, and it has not gone through a security audit of any sort. When the time comes to launch your site, see Chapter 20 for information on how to deploy Django.

尽管对于开发来说,这个开发服务器非常得棒,但一定要打消在产品级环境中使用该服务器的念头。在同一时间,该服务器只能可靠地处理一次单个请求,并且没有进行任何类型的安全审计。发布站点前,请参阅第 20 章了解如何部署 Django 。

Changing the Host or the Port

更改主机或端口

By default, the runserver command starts the development server on port 8000, listening only for local connections. If you want to change the servers port, pass it as a command-line argument:

默认情况下, runserver 命令在 8000 端口启动开发服务器,且只监听本机连接。要想要更改服务器端口的话,可将端口作为命令行参数传入:

python manage.py runserver 8080

You can also change the IP address that the server listens on. This is especially helpful if youd like to share a development site with other developers. The following:

还可以改变服务器监听的 IP 地址。要和其他开发人员共享同一开发站点的话,该功能特别有用。下面的命令:

python manage.py runserver 0.0.0.0:8080

will make Django listen on any network interface, thus allowing other computers to connect to the development server.

会让 Django 监听所有网络接口,因此也就让其它电脑可连接到开发服务器了。

Now that the servers running, visit http://127.0.0.1:8000/ with your Web browser. Youll see a Welcome to Django page shaded a pleasant pastel blue. It worked!

既然服务器已经运行起来了,现在用网页浏览器访问 http://127.0.0.1:8000/ 。 你应该可以看到一个欢快的淡蓝色所笼罩的 Django 欢迎页面。一切正常!

Whats Next?

下一章讲

Now that you have everything installed and the development server running, in the next chapter youll write some basic code that demonstrates how to serve Web pages using Django.

既然一切都已经安装完毕,开发服务器也已经运行起来了,下一章中,让我们编写一些基础代码,演示如何使用 Django 提供网页服务。

Docutils System Messages

System Message: ERROR/3 (<string>, line 396); backlink

Unknown target name: “http://code.djangoproject.com”.

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