Django part01

来源:互联网 发布:老滚捏脸数据 编辑:程序博客网 时间:2024/06/03 21:26

Writing your first Django app, part 1

Let’s learn by example.

我们从一个例子开始吧.

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

通过这个教程

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.你可以通过运行以下的命令来告诉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”.

This tutorial is written for Django 1.10 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.

如果Django已经安装,你应该看到你安装的版本.如果还未安装,你会报一个“No module named django”的错误.

此教程适用于Django1.10,python3.4+.如果Django版本不匹配,你可以参考你所用的版本的教程,或者升级到最新的版本,如果你还在用python2.7,你需要稍

微调整代码,如注释所述.

See How to install Django for advice on how to remove older versions of Django and install a newer one.

Where to get help:

If you’re having trouble going through this tutorial, please post a message to django-users or drop by #django on irc.freenode.net to chat with other Django users who might be able to help.

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实例化的连接,包括数据库,配置,Django特有的选项和app特有的设置.

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

从命令行 cd  进入到你代码仓库的目录,然后运行以下命令:

$ django-admin startproject mysite

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).

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.

Let’s look at what startproject created:

起始项目创建了:

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/ 根目录就是你的项目的一个容器
  • manage.py: A command-line utility that lets you interact with this Django project in various ways. You can read all the details
  • manage.py: 一个让你用多种途径互相作用Django项目的通用命令行
  • aboutmanage.py in django-admin and 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. mysite.urls).
  • 里面的 mysite/ 目录是你项目的一个真正python包.其名称是Python包的名称,您将需要使用导入它里面的任何东西(例如: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, read more about packages in the official Python docs.
  • mysite/ __init__.py:一个告诉python此目录应该被视为一个python包的空文件.
  • mysite/settings.py: Settings/configuration for this Django project. Django settings will 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:此Django项目的URL声明;一个"目录表"
  • mysite/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGI for more details.
  • mysite/wsgi.py:与WSGI兼容的web服务入口点

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:

确认你的Django项目是否运作.更改到外面的 mysite 目录(如果你还没有),运行下面的密令:

$ python manage.py runserver

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

你会在命令行看到以下输出:

Performing system checks...System check identified no issues (0 silenced).You have unapplied migrations; your app may not work properly until they are applied.Run 'python manage.py migrate' to apply them.December 22, 2016 - 15:50:53Django version 1.10, using settings 'mysite.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-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写的轻量的Web服务.我们已经在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.

笔记时间:~

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/ .你会看到愉快的,浅蓝色的“Welcome to Django”页面.它运行起来啦!

Changing the port

By default, the runserver command starts the development server on the internal IP at port 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:

$ python manage.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:

$ python manage.py runserver 0.0.0.0:8000

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

Automatic reloading of 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.

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自带一个通用的自动生成的app基础目录结构.因此你可以专注于写代码而不是创建目录.

Projects vs. apps

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 of mysite.

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

要创建一个app ,请确保你在 manage.py的同级目录.然后键入此命令:

$ python manage.py startapp polls

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:

写下第一个view(视图). 打开 polls/view.py 写入如下python代码:

polls/views.py
from django.http import HttpResponsedef 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可接受的最简单的view.要调用视图,我们需要映射到一个URL --对此我们需要一个URL配置.

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

要在polls目录创建一个URLconf,创建一个 urls.py 的文件.现在你的app看起来应该是这样:

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 文件里包含了如下代码:

polls/urls.py
from django.conf.urls import urlfrom . import viewsurlpatterns = [    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:

下一个步骤指向polls.urls模块下的URLconf. 在 mysite/urls.py 里,为添加一条 django.conf.urls.include  并且 插入一个 include() 到urlpatterns 列表,现在你看到:

mysite/urls.py
from django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [    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 the include() 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() 方法允许引用其他URLconfs,需要注意的是include()方法的正则表达式并非一个 $ (结束符)而是 / (斜杠).无论何时Django遇到include(),它砍掉任何匹配到的那个点然后发送剩下的字符串到URLconf进一步处理.

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()背后的理念是让即插即用的URLs更简单.

When to use include()

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

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.

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

你现在有一个和URLconf连起来的 index 视图.确认他是否在工作,运行下面的命令:

$ python manage.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 view 的文字  “Hello, world. You’re at the polls index.” 

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

url() 方法传递四个参数,两个必须的: regex 和 view,两个可选的: kwargs 和 name. 那么此刻,值得温习一下这四个参数是干什么的.

url() argument: 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

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

注意这些正则不搜索GET和POST参数,或域名.例如:~

If you need help with regular expressions, see Wikipedia’s entry and the documentation of the re module. 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.

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() argument: view¶

When Django finds a regular expression match, Django calls the specified view function, with an HttpRequest 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¶

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¶

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.


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

0 0