剑客
关注科技互联网

Django 1.11官方教程翻译

一直以来由于英语废所以极端抵触看英文文档。感觉人还是要逼一下自己,所以就有了这篇翻译。如果有翻译错误的地方欢迎在评论中指正。

Let’s learn by example.

Throughout this tutorial, we’ll walk you through the creation of a basic poll application.

让我们通过样例来学习Django吧。

本教程将通过一个简单的投票应用来让您熟悉Django。

It’ll consist of two parts:

  • A public site that lets people view polls and vote in them.
  • An admin site that lets you add, change, and delete polls.

这个项目包括两个部分:

  • 一个对外显示的网站,以供人们投票。
  • 一个管理网站,您可以在其中对结果增删改查。

We’ll assume you have Django installed already. You can tell Django is installed and which version by running the following command:

我们假定你已经 安装Django
了(如果你已经安装了pip,也可以通过pip install Django来安装),你可以通过如下命令来查看你是否安装了Django。

$ python -m django --version

If Django is installed, you should see the version of your installation. If it isn’t, you’ll get an error telling “No module named django”.

如果你已经安装了Django,那么你应该会看到Django的版本号,反之,你将会看到错误提示“No module named django”。

This tutorial is written for Django 1.11 and Python 3.4 or later. If the Django version doesn’t match, you can refer to the tutorial for your version of Django by using the version switcher at the bottom right corner of this page, or update Django to the newest version. If you are still using Python 2.7, you will need to adjust the code samples slightly, as described in comments.

本教程适用于Django1.11及以上,python版本要求为python3.4及以上,如果版本不匹配,你可以尝试下载更新版本的Django或者寻找之前版本的教程,如果你使用的是python2.7,那么你可能需要稍微调整你的代码,我们会把改动写在注释中。

Creating a project

创建项目

If this is your first time using Django, you’ll have to take care of some initial setup. Namely, you’ll need to auto-generate some code that establishes a Django project – a collection of settings for an instance of Django, including database configuration, Django-specific options and application-specific settings.

如果这是你第一次使用Django,你需要做一些初始化工作,也就是说我们会自动生成一些代码来帮你建立一个Django 项目
。主要是一些配置信息,包括数据库配置、Django选项和特定的应用程序设置。

From the command line, cd into a directory where you’d like to store your code, then run the following command:

首先,在命令行切换到你想储存你Django代码的位置,执行接下来的命令:

$ django-adminstartprojectmysite

This will create a mysite directory in your current directory. If it didn’t work, see Problems running django-admin.

它会在当前目录创建一个名为mysite的文件夹,如果没有,请查看 帮助

Note

You’ll need to avoid naming projects after built-in Python or Django components. In particular, this means you should avoid using names like django (which will conflict with Django itself) or test (which conflicts with a built-in Python package).

需要注意的是
,你的项目名称尽量避免和python和Django的某些组件重名,例如django(和Django重名)和test(与python包重名)

Where should this code live?

If your background is in plain old PHP (with no use of modern frameworks), you’re probably used to putting code under the Web server’s document root (in a place such as /var/www). With Django, you don’t do that. It’s not a good idea to put any of this Python code within your Web server’s document root, because it risks the possibility that people may be able to view your code over the Web. That’s not good for security.

Put your code in some directory
outside

of the document root, such as /home/mycode.

Django代码应该放在什么地方?

如果你使用的是老式的PHP(没有现代框架)你可能习惯于把代码放在Web服务器根目录下(例如/var/www)。而在Django中不建议你这么做,因为这是一个不好的习惯,因为这增加了人们通过网络直接查看你代码的可能性,这会降低网站的安全性。

把你的代码放在 别的
地方,例如/home/mycode

Let’s look at what startproject created:

我们来看看 startproject
创建了什么:

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

These files are:

这些文件的含义如下:

  • The outer mysite/root directory is just a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.

外部的mysite仅仅是你项目的容器而已,它的名字不会影响到Django的运行,你可以把它改成你喜欢的名字。

  • py: A command-line utility that lets you interact with this Django project in various ways. You can read all the details about manage.pyin django-admin and manage.py.

manage.py:是一个供你在命令行使用的管理工具,你可以通过它来管控你的项目,你可以点击 这里
查看更多细节。

The inner mysite/directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. urls).

内部的mysite目录才是你的项目本体,它的名字就是你的包名,如果你需要引用它以及内部的模块,你可以直接import它(例如:mysite.urls)。

mysite/__init__.py: An empty file that tells Python that this directory should be considered a Python package. If you’re a Python beginner, readin the official Python docs.

mysite/__init__.py:一个空文件,它的作用只是向python表明这是一个python包。如果你还是不太清楚,建议你先阅读 python文档中包的部分

mysite/settings.py: Settings/configuration for this Django project. Django settingswill tell you all about how settings work.

mysite/settings.py:设置/配置这个Django项目,点击 这里
查看配置是如何工作的。

mysite/urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site. You can read more about URLs in URL dispatcher.

mysite/urls.py:这是这个项目的url声明,也是你网站的目录,也可以查看 url调度
获取更多细节。

mysite/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGIfor more details.

mysite/wsgi.py:一个兼容WSGI入口点的Web服务器为您服务。参阅 如何使用WSGI

The development server

开发服务器

Let’s verify your Django project works. Change into the outer mysite directory, if you haven’t already, and run the following commands:

让我们来验证你的服务器能否正常运作吧。切换到外层的mysite目录,输入以下命令:

$ pythonmanage.py runserver

You’ll see the following output on the command line:

你将会看到如下输出:

Performingsystemchecks...
 
 
 
Systemcheckidentifiednoissues (0 silenced).
 
 
 
Youhaveunappliedmigrations; yourappmaynot workproperlyuntiltheyareapplied.
 
Run 'python manage.py migrate' to applythem.
 
 
 
October 06, 2016 - 15:50:53
 
Djangoversion 1.11, usingsettings 'mysite.settings'
 
Startingdevelopmentserverathttp://127.0.0.1:8000/
 
QuittheserverwithCONTROL-C.

Note

Ignore the warning about unapplied database migrations for now; we’ll deal with the database shortly.

注意

我们现在暂时忽略数据库迁移的警告,稍后我们会进行处理。

You’ve started the Django development server, a lightweight Web server written purely in Python. We’ve included this with Django so you can develop things rapidly, without having to deal with configuring a production server – such as Apache – until you’re ready for production.

你已经启动了一个由Django开发的服务器了,这是一个纯python编写的轻量级服务器,我们将这个服务器内置在Django中,所以你可以快速开发项目而无需花精力去思考如何配置生产服务器(就像Apache那样),直到你已经准备好生产了为止。

Now’s a good time to note:
don’t

use this server in anything resembling a production environment. It’s intended only for use while developing. (We’re in the business of making Web frameworks, not Web servers.)

提前打个预防针:不要将这个服务器用于生产环境中,这仅仅只是一个框架,不是一个Web服务器,所以不要开发环境之外使用这个服务器。

Now that the server’s running, visit http://127.0.0.1:8000/
with your Web browser. You’ll see a “Welcome to Django” page, in pleasant, light-blue pastel. It worked!

现在服务器已经运行,访问 http://127.0.0.1:8000/
你将会看到Django的欢迎界面。

Changing the port

更改端口

By default, the runserver command starts the development server on the internal IP at port 8000.

默认设置中,runserver命令会在8000端口上启动服务器。

If you want to change the server’s port, pass it as a command-line argument. For instance, this command starts the server on port 8080:

如果你想改变服务器的端口,下面的命令会在8080端口启动服务器。

$ pythonmanage.py runserver 8080

If you want to change the server’s IP, pass it along with the port. So to listen on all public IPs (useful if you want to show off your work on other computers on your network), use:

如果你想改变服务器的IP,从而使该服务器可以在公网上被访问(当你想要炫耀自己所做的事情时这就变得很重要了),请使用如下命令:

$ pythonmanage.py runserver 0.0.0.0:8000

Full docs for the development server can be found in the runserver reference.

关于runserver的全部文档你可以在这里查阅

Automatic reloading of 
runserver

runserver自动重载

The development server automatically reloads Python code for each request as needed. You don’t need to restart the server for code changes to take effect. However, some actions like adding files don’t trigger a restart, so you’ll have to restart the server in these cases.

根据需要,开发服务器会自动为每个请求重载python代码,你不需要为了修改python代码而重启服务器。然而,某些操作(例如添加文件)不会触发重载,所以这些情况下你必须重启服务器。

Creating the Polls app

创建投票应用

Now that your environment – a “project” – is set up, you’re set to start doing work.

现在你的环境已经配置完毕,你已经创建了一个项目,现在你要为这个项目添砖加瓦,使它运作起来。

Each application you write in Django consists of a Python package that follows a certain convention. Django comes with a utility that automatically generates the basic directory structure of an app, so you can focus on writing code rather than creating directories.

你在Django中写的每一个应用都会被看成一个遵守一定规范的python包。Django自带了一个实用的小程序,它会自动的生成程序的基本目录结构,所以你可以从目录地狱中解脱出来,从而专心于代码的编写。

Projects vs.

A


pps

项目与应用

What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

项目和应用有什么区别呢?应用会做一些实际的工作,例如一个网络博客系统、一个公共数据库或者一个简单的投票应用。而一个项目则是配置、应用和特定网站的集合,一个项目可以包含多个应用,一个应用也可以被多个项目共享。

Your apps can live anywhere on your Python path. In this tutorial, we’ll create our poll app right next to your manage.py file so that it can be imported as its own top-level module, rather than a submodule ofmysite.

你的应用代码可以放置在 python路径
下的任何位置,在本教程中,我们会在manage.py文件的旁边创建我们的投票应用,这样我们在引入的时候可以将这个应用作为顶级模块而不是mysite的子模块引入。

To create your app, make sure you’re in the same directory as manage.py and type this command:

我们将目录切换到manage.py所在的目录并输入以下命令:

$ pythonmanage.py startapppolls

That’ll create a directory polls, which is laid out like this:

这会创建一个名为polls的目录,它的结构如下:

polls/
 
    __init__.py
 
    admin.py
 
    apps.py
 
    migrations/
 
        __init__.py
 
    models.py
 
    tests.py
 
    views.py

This directory structure will house the poll application.

这就是我们投票应用的目录了。

Write your first view

创建你的第一个视图

Let’s write the first view. Open the file polls/views.py and put the following Python code in it:

让我们开始写第一个视图吧。打开polls/views.py并在其中写下如下代码:

from django.httpimport HttpResponse
 
 
def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

This is the simplest view possible in Django. To call the view, we need to map it to a URL – and for this we need a URLconf.

这是Django的最简视图了,为了调用这个视图,我们需要把他映射到url中,为此我们需要一个url配置文件

To create a URLconf in the polls directory, create a file called urls.py. Your app directory should now look like:

在polls目录下创建urls.py文件。现在你的应用目录应该是这样的。

polls/
 
    __init__.py
 
    admin.py
 
    apps.py
 
    migrations/
 
        __init__.py
 
    models.py
 
    tests.py
 
    urls.py
 
    views.py

In the polls/urls.py file include the following code:

在polls/urls.py文件中写下如下代码:

from django.conf.urlsimport url
 
from . import views
 
urlpatterns = [
    url(r'^$', views.index, name='index'),
]

The next step is to point the root URLconf at the polls.urls module. In mysite/urls.py, add an import fordjango.conf.urls.include and insert an include() in the urlpatterns list, so you have:

下一步是将项目的url配置指向polls.urls模块。在mysite/urls.py中,添加一个django.conf.urls.include 的引用,并且在urlpatterns中插入一个include(),代码如下:

from django.conf.urlsimport include, url
from django.contribimport admin
 
urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
]

The include() function allows referencing other URLconfs. Note that the regular expressions for theinclude() function doesn’t have a $ (end-of-string match character) but rather a trailing slash. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

include()函数允许引用其他的url配置文件。需要注意的一点是,include()功能的正则表达式没有$符号(代表着匹配结尾字符)的,而是以一个斜杠结尾。无论何时Django遇到 include(),它会截取下匹配的部分然后将剩余的字符串送到包含的URL配置文件中做进一步处理。

The idea behind include() is to make it easy to plug-and-play URLs. Since polls are in their own URLconf (polls/urls.py), they can be placed under “/polls/”, or under “/fun_polls/”, or under “/content/polls/”, or any other path root, and the app will still work.

include()的设计思路是更方便的实现URL的即插即用。由于这个投票应用有它自己的URL配置文件(polls/urls.py),它可以被放置在/polls/下,也可以在/fun_polls/下,或者在/content/polls/下,其他根路径也是可以的,应用仍然可以正常工作。

When to use 
include()

什么时候需要使用include()

You should always use include() when you include other URL patterns. admin.site.urls is the only exception to this.

当你想要包含其他的url路径时你总是会用到include()的。当然admin.site.urls例外。

Doesn’t match what you see?

和你看到的不匹配?

If you’re seeing include(admin.site.urls) instead of just admin.site.urls, you’re probably using a version of Django that doesn’t match this tutorial version. You’ll want to either switch to the older tutorial or the newer Django version.

如果你看到的是include(admin.site.urls)而不是admin.site.urls,你可能使用的Django版本和当前教程的版本不匹配。你可以查阅旧版本的课程或者使用更新的Django版本

You have now wired an index view into the URLconf. Lets verify it’s working, run the following command:

你现在已经将一个index视图添加到了url配置文件中,我们来看看他是否能正常工作吧。执行下面的语句:

$ pythonmanage.py runserver

Go to http://localhost:8000/polls/
in your browser, and you should see the text “
Hello, world. You’re at the polls index.

”, which you defined in the index view.

现在在浏览器中打开 http://localhost:8000/polls/
看看结果吧,你应该可以看到你在index视图中所写的“Hello, world. You’re at the polls index.”

The url() function is passed four arguments, two required: regex and view, and two optional: kwargs, andname. At this point, it’s worth reviewing what these arguments are for.

url()函数传递四个参数,两个是必选的:regex和view,另两个则是可选的:kwargs和name。我们来回顾一下这些参数吧

url()
 argument: regex

url()参

:regex

The term “regex” is a commonly used short form meaning “regular expression”, which is a syntax for matching patterns in strings, or in this case, url patterns. Django starts at the first regular expression and makes its way down the list, comparing the requested URL against each regular expression until it finds one that matches.

regex是正则表达式(regular expression)的常见缩写,正则表达式是一种字符串匹配模式,在这个函数中被用来匹配url。Django会按顺序检索这个正则表达式的list,匹配请求的url直到某条正则表达式匹配为止。

Note that these regular expressions do not search GET and POST parameters, or the domain name. For example, in a request to https://www.example.com/myapp/, the URLconf will look for myapp/. In a request tohttps://www.example.com/myapp/?page=3, the URLconf will also look for myapp/.

需要注意的是,这些正则表达式不搜索域名和GET和POST的参数。举例来说,对https://www.example.com/myapp/ 的请求,url配置文件只会去搜索myapp/。https://www.example.com/myapp/?page=3这样的请求,配置文件也会过滤掉参数,只检索myapp/

If you need help with regular expressions, see Wikipedia’s entry and the documentation of themodule. Also, the O’Reilly book “Mastering Regular Expressions” by Jeffrey Friedl is fantastic. In practice, however, you don’t need to be an expert on regular expressions, as you really only need to know how to capture simple patterns. In fact, complex regexes can have poor lookup performance, so you probably shouldn’t rely on the full power of regexes.

如果你想看一些正则表达式的相关资料,可以参考 wiki百科的条目
re模块的文档
。另外Jeffrey Friedl的书《Mastering Regular Expressions》真的是太棒了。然而在实际工作中,你不需要成为一个正则专家,因为你只需要如何去捕捉简单的字段就好,事实上,复杂的正则表达式在性能上通常表现不能令人满意,所以,不建议你完全依赖正则表达式。

Finally, a performance note: these regular expressions are compiled the first time the URLconf module is loaded. They’re super fast (as long as the lookups aren’t too complex as noted above).

最后提一下性能相关:这些正则表达式将会在url配置文件加载的同时被编译。所以他们的查找会很快的(除了上面提到的情况)。

url()
 argument: view

url()参数:view

When Django finds a regular expression match, Django calls the specified view function, with anHttpRequest object as the first argument and any “captured” values from the regular expression as other arguments. If the regex uses simple captures, values are passed as positional arguments; if it uses named captures, values are passed as keyword arguments. We’ll give an example of this in a bit.

当Django找到一个正则匹配时,Django就会将 HttpRequest对象
作为第一个参数,连同其他被正则表达式捕获的值作为参数传递给视图函数。如果正则表达式只用于简单的捕捉,值就会作为位置参数传递进去,如果使用键捕获,则会把值作为关键字传递。我们将在接下来的教程中给出样例。

url()
 argument: kwargs

url()参数:kwagrs

Arbitrary keyword arguments can be passed in a dictionary to the target view. We aren’t going to use this feature of Django in the tutorial.

任何关键字都可以传递到目标视图中,但是在本教程中并不会使用这一特性。

url()
 argument: name

url()参数:name

Naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from within templates. This powerful feature allows you to make global changes to the URL patterns of your project while only touching a single file.

为你的url命名,你可以在Django的其他地方简洁明了的引用它,尤其是从模版中引用,这种强大的功能可以让你在你的项目中仅仅修改一个文件就能全局的改变url对象

When you’re comfortable with the basic request and response flow, read part 2 of this tutorial to start working with the database.

当你熟悉了基本的请求和响应流程后,阅读 第二部分
吧,我们将开始着手处理数据库相关。

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址