已經同步到gitbook形庭,想閱讀的請轉到gitbook: Django 1.10 中文文檔
Let’s learn by example.
讓我們通過例子來學習
Throughout this tutorial, we’ll walk you through the creation of a basic poll application.
通過本教程,我們將帶著你創(chuàng)建一個基本的投票應用
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,你可以輸入以下命令來驗證和查看你所安裝的版本:
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辅柴,你將看到你安裝的版本好。如果沒有瞭吃,將會報一個“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 1.10 以及 Python 3.4+版本編寫碌嘀。如果你的Django版本不符, 如果Django版本不符歪架,可以通過當前頁面右下角的版本轉換器查看適用于你所使用的版本的Django教程股冗,或者把Django升級到最新的版本。 如果你還在使用2.7版本的Python和蚪,你將需要按照注釋中的內容稍微調整一下示例代碼止状。
See How to install Django for advice on how to remove older versions of Django and install a newer one.
關于如何卸載舊版本并安裝新版本的Django,請參考How to install Django
- 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.
- 如何獲得幫助:
在本教程中惠呼,你有任何問題导俘,都可以發(fā)消息給django 開發(fā)人員 或者訪問 #django on irc.freenode.net網站,與其他Django開發(fā)者交流尋求幫助剔蹋。
Creating a project
創(chuàng)建項目
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.
From the command line, cd
into a directory where you’d like to store your code, then run the following command:
如果這是你第一次使用Django旅薄,你需要注意一下初始化設置。換句話說泣崩,你需要使用命令行來自動創(chuàng)建一個Django項目 --一個Django框架開發(fā)的網站少梁,包括數據庫設置,針對Django的配置以及針對app應用的配置矫付。
在命令行中凯沪,cd到你想要報錯你項目代碼的目錄,并執(zhí)行一下命令:
django-admin startproject mysite
This will create a mysite
directory in your current directory. If it didn’t work, see Problems running django-admin.
這將會在你的當前目錄下創(chuàng)建一個mysite目錄买优。如果沒有妨马,請查看Problems running django-admin.
- 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.
- 代碼應該存在哪里
如果你有過普通老久的PHP開發(fā)背景(沒有使用過現代流行框架)烘跺,你可能會把代碼保存到web服務器的文檔根目錄下(如/var/www)湘纵。但在Django里,請不要這樣做滤淳。將任何的python代碼放在web服務器根目錄是有很大風險的梧喷,因為別人可能通過網站查看到你的源代碼。這違背了安全原則脖咐。
將你的代碼放置在Web服務器根目錄以外的地方铺敌,例如/home/mycode。
Let’s look at what startproject created:
讓我們看一下startproject命令創(chuàng)建了哪些文件和目錄:
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.
manage.py: A command-line utility that lets you interact with this Django project in various ways. You can read all the details about manage.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/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/settings.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work.
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/wsgi.py: An entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGIfor more details.
這些文件是:
外層的mysite/根目錄僅僅是一個項目容器屁擅。它的命名對Django無關偿凭,你可以把它重命名為任何你喜歡的名字。
manage.py:一個命令行工具煤蹭,可以使你用多種方式對Django項目進行交互笔喉。你可以在django-admin和manage.py中讀到關于manage.py的所有細節(jié)。
內層的mysite/目錄是你的項目的真正的Python包硝皂。它是你導入任何東西時將需要使用的Python包的名字(例如 mysite.urls。
mysite/init.py:一個空文件作谭,它告訴Python這個目錄應該被看做一個Python包稽物。如果你是一個Python初學者,關于包的更多內容請閱讀Python的官方文檔)折欠。
mysite/settings.py:該Django 項目的設置/配置贝或。Django 設置 將告訴你這些設置如何工作。
mysite/urls.py:該Django項目的URL聲明锐秦;你的Django站點的“目錄”咪奖。
你可以在URL 轉發(fā)器 中閱讀到關于URL的更多內容。
- mysite/wsgi.py:用于你的項目的與WSGI兼容的Web服務器入口酱床。
更多細節(jié)請參見如何利用WSGI進行部署羊赵。
**
The development server**
開發(fā)服務器
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.
March 01, 2017 - 15:50:53
Django version 1.10, using settings 'mysite.settings'Starting development server at [http://127.0.0.1:8000/](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.
- 注意
暫時忽略關于未應用的數據庫遷移昧捷,我們很快會講到database
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開發(fā)服務器,一個輕量級的純python寫的web服務器罐寨。我們集成在了Django內靡挥,這樣你就可以快速的開發(fā)產品,直到你準備好上線前都無需配置生產服務器--比如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!
友情提示:千萬不要在類生產服務器使用鸯绿,它僅能在開發(fā)中使用跋破。(我們重點是開發(fā)web框架簸淀,而不是web服務器)
服務器運行后,瀏覽器訪問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.
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:
- 更改端口
默認默認情況下饿悬,runserver 命令啟動的開發(fā)服務器運行在內部IP的8000端口令蛉。如果你想更改端口,需要加個參數狡恬,比如說珠叔,下面這個命令開啟了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:
如果你想更改綁定的服務IP,可把IP和端口一起作為參數弟劲。因此若要監(jiān)聽所有外網IP(如果你想在局域網內與其他人開發(fā)同一站點的話祷安,該功能非常有用),輸入命令:
python manage.py runserver 0.0.0.0:8000
Full docs for the development server can be found in the runserver reference.
開發(fā)服務器的所有文檔可以在runserver的參考手冊中找到兔乞。
- 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.
- runserver的自動重載
開發(fā)服務器會根據需要自動重新載入Python代碼汇鞭。 你不必為了使更改的代碼生效而重啟服務器。 然而庸追,一些行為比如添加文件霍骄,不會觸發(fā)服務器的重啟,所以在這種情況下你需要手動重啟服務器淡溯。
創(chuàng)建投票應用
Now that your environment – a “project” – is set up, you’re set to start doing work.
現在你已經在你的開發(fā)環(huán)境新建了一個項目读整,你可以在上面開始工作了
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.
你創(chuàng)建的每一個django應用,都必須包含一個約定俗成的python包咱娶。Django自帶了一個自動創(chuàng)建app目錄結構的工具米间,這樣你可以專心碼代碼而不是去創(chuàng)建那些目錄
- 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.
項目和應用之間有什么區(qū)別呢?一個應用是一個web程序膘侮,它負責特定的工作--比如說一個博客系統屈糊,一個存儲公共文檔的數據庫系統或者一個簡單的投票應用。而項目是一個網站配置和應用的集合琼了。項目可以包括多個應用逻锐,一個應用也可以從屬于多個項目
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:
你的應用可以放在Python path的任何位置。在本教程表伦,我們將投票應用放在manage.py文件同級目錄下谦去,這樣就可以作為頂層模塊導入,而不是mysite的子模塊蹦哼。進入到manage.py的同級目錄下鳄哭,輸入一下命令:
python manage.py startapp polls
That’ll create a directory polls, which is laid out like this:
命令將會創(chuàng)建一個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/views.py,輸入以下代碼:
from django.http import 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.
To create a URLconf in the polls directory, create a file called urls.py. Your app directory should now look like:
這是Django里最簡單的view函數妆丘。為了調用該函數锄俄,我們需要編輯URLconf.在polls目錄創(chuàng)建URLconf,也就是創(chuàng)建一個名為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:
from django.conf.urls import 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 for django.conf.urls.include and insert an include() in the urlpatterns list, so you have:
下一步就是讓項目主urls文件指向polls.urls這個模塊奶赠。在mysite/urls.py,導入django.conf.urls.include模塊药有,并且添加到urlpatterns列表毅戈,所以mysite/urls.py如下:
# mysite/urls.py
from django.conf.urls import include, url
from django.contrib import 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 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()函數后,會截斷正則表達式匹配到的字符串宦言,然后將剩下的url傳遞到所incloude的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()的設計思想是方便即插即用。由于polls在它自己的URLconf(polls/urls.py)奠旺,你可以用“/polls/”, “/fun_polls/”, “/content/polls/”或者其他任意主目錄隨意替換蜘澜,它仍可以正常工作。
When to use include()
You should always use include() when you include other URL patterns.admin.site.urls is the only exception to this.
當你需要引入其他url時响疚,盡量使用include()鄙信,唯一的特例是patterns.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版本可能與本教程不符扮碧。你應該切換到舊的教程教程或
You have now wired an index view into the URLconf. Lets verify it’s working, run the following command:
你已經將view函數index()映射到URLconf,讓我們來驗證它能否正常工作杏糙,運行如下命令:
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.
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.
在你的瀏覽器訪問http://localhost:8000/polls/,你將看到“Hello, world. You’re at the polls index.”蚓土,這就是我們剛剛在index view函數定義的宏侍。
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.
“正則”是正則表達式的通用縮寫确丢,它是一種匹配字符串或url地址的語法绷耍。在這里就是指url patterns。Django拿著用戶請求的url地址鲜侥,在urls.py文件中對urlpatterns列表中的每一項條目從頭開始進行逐一對比褂始,直到匹配為止。
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 to https://www.example.com/myapp/?page=3, the URLconf will also look for myapp/.
需要注意的是描函,regex不會去匹配GET或POST參數或域名崎苗,例如對于https://www.example.com/myapp/狐粱, regex只嘗試匹配myapp/。對于https://www.example.com/myapp/?page=3, regex也只嘗試匹配myapp/胆数。
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.
如果你想深入研究正則表達式肌蜻,可以參考Wikipedia’s entry 以及 re 模塊的文檔,由作者Jeffrey Friedl出版的O’Reilly “Mastering Regular Expressions”書籍也非常不錯必尼。但是實踐中蒋搜,你不需要多高深的正則表達式知識,因為你只需要知道如何匹配簡單的規(guī)則判莉。事實上豆挽,復雜的正則表達式查詢性能會比較差,所以盡可能不用正則的復雜功能
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).
最后骂租,關于性能問題:正則表達式會進行預先編譯當URLconf模塊加載的時候祷杈,因此它的匹配搜索速度非常快渗饮,你通常感覺不到但汞。
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.
當正則表達式匹配到某個條目時,自動將封裝的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 tutorialto start working with the database.
對你的URL進行命名之景,可以讓你能夠在Django的任意處斤富,尤其是模板內顯式地引用它。這個強大的功能锻狗,僅僅通過創(chuàng)建一個文件就可以讓你在項目里任意修改URL patterns這個全局變量的值满力。如果你已經掌握了基本的request和response的過程,那就閱讀教程第二部分 數據庫開始學習數據庫相關