diff --git a/files/zh-tw/learn/server-side/django/admin_site/index.html b/files/zh-tw/learn/server-side/django/admin_site/index.html deleted file mode 100644 index 6829fdafb4ba18..00000000000000 --- a/files/zh-tw/learn/server-side/django/admin_site/index.html +++ /dev/null @@ -1,354 +0,0 @@ ---- -title: 'Django Tutorial Part 4: Django admin site' -slug: Learn/Server-side/Django/Admin_site -translation_of: Learn/Server-side/Django/Admin_site ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Django/Models", "Learn/Server-side/Django/Home_page", "Learn/Server-side/Django")}}
- -

現在,我們已經為本地圖書館網站 LocalLibrary 創建了模型,我們接下來使用 Django 管理網站,去添加 一些 “真實的“ 書本數據。首先,我們展示如何用管理網站註冊模型,然後展示如何登錄和創建一些數據。本文最後,我們介紹可以進一步改進管理網站的建議。

- - - - - - - - - - - - -
前提:先完成: Django Tutorial Part 3: Using models.
目標: -

了解 Django 管理站的優點與侷限,並使用它來為我們的模型新增一些資料。

-
- -

概覽

- -

Django 管理應用程序可以使用您的模型,自動構建可用於創建,查看,更新和刪除記錄的網站區域。這可以在開發過程中,節省大量的時間,從而很容易測試您的模型,並了解您是否擁有正確的數據。根據網站的類型,管理應用程序也可用於管理生產中的數據。 Django 項目建議僅用於內部數據管理(即僅供管理員或組織內部人員使用),因為以模型為中心的方法,不一定是所有用戶最好的界面,並且暴露了大量不必要的關於模型的細節。

- -

創建基礎項目時,自動完成所有的配置文件,包含您的網站中的管理應用程序在內(有關所需實際依賴關係的信息,如有需要請看 Django docs here)。其結果是,要將模型添加到管理應用程序,你必須做的,僅僅是註冊他們。在本文末尾,我們將簡要介紹,如何進一步配置管理區域,以更好地顯示我們的模型數據。

- -

註冊模型後,我們將展示,如何創建一個新的 “超級用戶”,登錄到該網站,並創建一些書籍,作者,書籍實例和書籍類別。這些將有助於測試我們將在下一個教程中,開始創建的視圖和模板。

- -

註冊模型(Registering models )

- -

首先,我們從 catalog app 中打開 admin.py (/locallibrary/catalog/admin.py),目前它長的像下面區塊,注意它已經幫你導入 django.contrib.admin

- -
from django.contrib import admin
-
-# Register your models here.
- -

將下方的程式碼複製貼在 admin.py 文件下方以註冊所有模型,這段程式碼簡單來說就是先將模型導入,再呼叫 admin.site.register 函式來註冊每個模型。

- -
from .models import Author, Genre, Book, BookInstance
-
-admin.site.register(Book)
-admin.site.register(Author)
-admin.site.register(Genre)
-admin.site.register(BookInstance)
- -
注意:如果你在上一章節最後有接受挑戰並建立一個書本的「語言模型」 (查看模型教學文章),你必需也要導入並註冊該模型!
- -

這是註冊模型最簡單的方式。

- -

而管理站則是高度用戶化的,我們會在接下來繼續說明其它註冊你的模型的方式。

- -

創建超級用戶(Creating a superuser)

- -

為了能夠登入管理站,我們需要一個有啟用員工狀態(Staff status)的使用者帳號,另外為了要能檢視與產生資料,我們也需要讓這個使用者帳號擁有管理所有物件的權限,因此,你可以透過 manage.py 來創建一個擁有所有網站存取權限的超級用戶(superuser)。

- -

在與 manage.py 同一個資料夾中執行下方指令,建立一個超級用戶,你會被提示要輸入「使用者名稱」、「使用者 e-mail」和「強度夠高的密碼」。

- -
python3 manage.py createsuperuser
- -

當完成指令輸入後,一個新的超級用戶就會被加進資料庫中,再來只要重新啟動開發用 server ,你便可以進行登入測試:

- -
python3 manage.py runserver
-
- -

登入並開始使用網站

- -

要登入網站,必須先連上 /admin URL (e.g. http://127.0.0.1:8000/admin) 並且輸入你的超級用戶的使用者名稱與密碼(你會被重新導向登入頁面,輸入你的帳密後會再回到 /admin URL)。

- -

網站中的這部分羅列了所有以我們安裝的 app 分組的模型,你可以點擊模型名稱進入陳列所有與其相關連資料的頁面,而你可以進一步編輯它們,或者你也可以直接點擊模型名稱旁邊的 Add 連結來開始創建該類型的資料。

- -

Admin Site - Home page

- -

點擊 Books 右邊的 Add 連結來新增一本新書(會產生如下方的對話方塊),可以去觀察每個字段(field)、小部件、提示文字(如果有的話)是如何對應到你的模型的。

- -

在字段中輸入值,你可以透過各個字段旁邊的 + 按鈕來新增「作者」或「書籍類別」(或者從列表中選擇你已經新增的值),當你完成後可以點選 SAVE, Save and add another, 或 Save and continue editing 來儲存該筆資料。

- -

Admin Site - Book Add

- -
-

注意:在這邊我們希望你花點時間在你的 app 中新增一些書本、作者和書及類型(例如:奇幻等)。請確保每位作者與每種書籍類型都分別關聯了一本以上的書(這在文章稍後的實作的時候,會讓你的列表與細節視圖更加豐富有趣)

-
- -

當你新增完書本後,點擊上方書籤的 Home 連結回到主要管理頁面,接著點擊 Books 連結來展示目前的書本清單(你也可以點及其他連結看看其他模型的列表),現在你已經加了幾本書,畫面應該會與下方截圖類似,你可以看到下方陳列了每本書的標題,這是我們在上一篇文章所提到的 Book 模型中的 __str__() 方法所回傳的值。

- -

Admin Site - List of book objects

- -

在列表中,如果要刪掉你不想要的書,只需要先勾選欲刪除書本的勾選方框,從動作下拉選單選擇刪除動作(delete action),接著點選 GO 按鈕即可,另外你也可以點選 ADD BOOK 按鈕來新增一本書。

- -

你可以點擊書名來編輯它,下方顯示的書本編輯頁面幾乎與 Add 頁面相同,主要差異在於頁面的標題(Change book)以及增加了 Delete, HISTORYVIEW ON SITE 按鈕(會有這個按鈕出現是因為我們之前在模型中有定義了 get_absolute_url() 的方法)

- -

Admin Site - Book Edit

- -

現在透過頁面上方的索引連結回到 Home 頁面,然後看看 AuthorGenre 列表,你在新增書本的時候應該已經新增了一些資料,不過你還可以再新增更多。

- -

你還沒有任何書本實例(Book Instances),因為這不會在建立書本時就產生(但你可以在新增 BookInstance 資料時新增 Book ,這是 ForeignKey 字段的性質)。現在回到 Home 頁面然後點擊 Book instances 的 Add 按鈕,畫面會呈現如下圖的頁面,注意第一列有個很長、全域唯一的 id 編碼,它可以用來區分每本書在圖書館裡的每個副本。

- -

Admin Site - BookInstance Add

- -

幫你的每本書都新增幾筆不同的資料,有些資料的狀態(Status)請設成 Available ,有些則設成 On loan,如果狀態為 not Available,那記得需要設定到期日(Due back date)。

- -

就是這樣!你現在已經學會了如何建立與使用管理站(administration site),你也為你的 Book, BookInstance, Genre, 和 Author 模型建立了幾筆資料,再來當我們建立好視圖(Views)以及模板(Templates)後,就會開始來使用它們。

- -

進階組態(Advanced configuration)

- -

Django 在「透過註冊模型的資訊建立管理站」這方面做得非常好:

- - - -

你可以進一步訂製介面讓它更好用,以下是你可以進一步做的:

- - - -

這部分我們將要來看幾個有助於改善 LocalLibrary 介面的小變化,包含了添加更多資訊到 BookAuthor 模型列表,以及改善編輯視圖的排版。我們不會改變 LanguageGenre 的模型外貌因為他們都各只有1個字段,這樣做沒好處!

- -

你可以在 The Django Admin site (Django Docs) 找到關於管理站訂製選擇的完整參考。

- -

註冊一個 模型管理 類別 (ModelAdmin class)

- -

為了要改變模型在管理站的陳列方式,你需要定義一個模型管理(ModelAdmin)類別 (他是用來描述排版的),並且將它與其他模型一起註冊。

- -

我們現在先從 Author 模型開始。打開 catalog app 中的 admin.py 檔案(/locallibrary/catalog/admin.py),並將先前註冊 Author 模型的程式碼註解(在程式碼前面加一個 # 前綴):

- -
# admin.site.register(Author)
- -

現在加上一個新的 AuthorAdmin 類別與註冊函式,如下方所示:

- -
# Define the admin class
-class AuthorAdmin(admin.ModelAdmin):
-    pass
-
-# Register the admin class with the associated model
-admin.site.register(Author, AuthorAdmin)
-
- -

現在我們要為 Book 以及 BookInstance 模型添加 ModelAdmin 類別,我們一樣要先把原本的註冊程式碼註解:

- -
#admin.site.register(Book)
-#admin.site.register(BookInstance)
- -

現在我們要創造並註冊新的模型;為了達到示範的目的,我們會使用 @register 裝飾器替代先前做法來註冊模型(這跟 admin.site.register() 的語法做的事情完全一樣):

- -
# Register the Admin classes for Book using the decorator
-@admin.register(Book)
-class BookAdmin(admin.ModelAdmin):
-    pass
-
-# Register the Admin classes for BookInstance using the decorator
-@admin.register(BookInstance)
-class BookInstanceAdmin(admin.ModelAdmin):
-    pass
- -

目前為止我們的管理類別都是空的(可以看到 "pass"),所以我們的管理行為都不會改變!現在我們可以來進一步定義我們的「特定模型的管理行為」。

- -

配置列表視圖(Configure list views)

- -

我們的 LocalLibrary 目前條列出所有作者,而他們都是使用以模型的 __str__() 方法產生的物件名稱。如過你只有少數幾個作者,那倒還好,但如果作者很多,你最後可能會有非常多副本。因此為了區別他們,或者你只是想呈現更多作者的有趣訊息,你可以使用「列表展示」(list_display)來位視圖添加額外的字段。

- -

將你的 AuthorAdmin 類別以下方程式碼取代。下方程式碼可以看出來,列表中被展示出來的字段名稱會被以需要的排序宣告為元組(tuple)形式。

- -
class AuthorAdmin(admin.ModelAdmin):
-    list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
- -

現在把網站導向作者列表,上方所設定的字段應該會被陳列出來,如下:

- -

Admin Site - Improved Author List

- -

至於我們的 Book 模型,我們將額外添加 authorgenre 兩樣。author 是一個ForeignKey 外鍵字段(一對一)關係,因此他將會透過關聯紀錄的 __str__() 值來表示。

- -

BookAdmin 類別以下方區段程式碼取代:

- -
class BookAdmin(admin.ModelAdmin):
-    list_display = ('title', 'author', 'display_genre')
- -

很不幸地,我們無法直接在 list_display 中指定「書籍類別」(genre field)字段,因為它是一個 ManyToManyField (多對多字段),因為如果這樣做會造成很大的資料庫讀寫「成本」,所以 Django 會預防這樣的狀況發生,因此,取而代之,我們將定義一個 display_genre 函式以「字串」形式得到書籍類別。(下方有定義此函式)

- -
-

Note: Getting the genre may not be a good idea here, because of the "cost" of the database operation. We're showing you how because calling functions in your models can be very useful for other reasons — for example to add a Delete link next to every item in the list.

-
- -

將以下程式碼添加到Book模型(models.py)。 這會從genre記錄的的頭三個值(如果有的話)創建一個字符串, 和創建一個在管理者網站中出現的short_description標題。

- -
    def display_genre(self):
-        """Create a string for the Genre. This is required to display genre in Admin."""
-        return ', '.join(genre.name for genre in self.genre.all()[:3])
-
-    display_genre.short_description = 'Genre'
-
- -

保存模型並更新管理員後,打開您的網站並轉到“Books”列表頁面; 您應該會看到類似以下的書籍清單:

- -

Admin Site - Improved Book List

- -

Genre 模型(如果定義了語言模型,則還有 Language 模型)都有一個欄位,因此沒有必要為它們創建其他模型以顯示欄位。

- -
-

注意: 更新 BookInstance 模型列表用來顯示狀態和預期的返回日期是有價值的。 我們在本文結尾處添加了一個挑戰!

-
- -

加入列表過濾器 (List Filter)

- -

當你的列表有很多個記錄時, 加入列表過濾器可以幫助你過濾想顯示的記錄。加入list_filter這個屬性就可以。請用以下的程式碼來取代原本的 BookInstanceAdmin 類別

- -
class BookInstanceAdmin(admin.ModelAdmin):
-    list_filter = ('status', 'due_back')
-
- -

現在的列表視圖右邊會多了一個過濾器。你可以選擇 dates 和 status 來做過濾:

- -

Admin Site - BookInstance List Filters

- -

組織詳細視圖佈局

- -

默認情況下,局部視圖按照模型中聲明的順序垂直排列所有字段。 您可以更改聲明的順序,顯示(或排除)哪些字段,使用分段來組織資訊,水平顯示還是垂直顯示字段,甚至管理表單中使用哪些編輯小部件。

- -
-

注意: LocalLibrary 模型相對簡單,因此我們無須更改佈局。 但我們仍然會進行一些更改,向您展示如何進行。

-
- -

控制那些欄位顯示並佈置

- -

更新你的 AuthorAdmin 類別用來新增 fields 這行,如同下列所示 (粗體):

- -
class AuthorAdmin(admin.ModelAdmin):
-    list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
-    fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')]
-
- -

fields 屬性僅按順序列出了要在表單上顯示的那些欄位。 默認情況下,字段是垂直顯示的,但是如果您進一步將它們分組到一個元組中,它們將水平顯示(如上面的“日期”字段中所示)。

- -

在您的網站上,轉到作者詳細信息視圖-現在應如下所示:

- -

Admin Site - Improved Author Detail

- -
-

注意: 您還可以使用 exclude 屬性來聲明要從表單中排除的屬性列表(將顯示模型中的所有其他屬性)。

-
- -

Sectioning the detail view

- -

You can add "sections" to group related model information within the detail form, using the fieldsets attribute.

- -

In the BookInstance model we have information related to what the book is (i.e. name, imprint, and id) and when it will be available (status, due_back). We can add these in different sections by adding the text in bold to our BookInstanceAdmin class.

- -
@admin.register(BookInstance)
-class BookInstanceAdmin(admin.ModelAdmin):
-    list_filter = ('status', 'due_back')
-
-    fieldsets = (
-        (None, {
-            'fields': ('book', 'imprint', 'id')
-        }),
-        ('Availability', {
-            'fields': ('status', 'due_back')
-        }),
-    )
- -

Each section has its own title (or None, if you don't want a title) and an associated tuple of fields in a dictionary — the format is complicated to describe, but fairly easy to understand if you look at the code fragment immediately above.

- -

Now navigate to a book instance view in your website; the form should appear as shown below:

- -

Admin Site - Improved BookInstance Detail with sections

- -

Inline editing of associated records

- -

Sometimes it can make sense to be able to add associated records at the same time. For example, it may make sense to have both the book information and information about the specific copies you've got on the same detail page.

- -

You can do this by declaring inlines, of type TabularInline (horizonal layout) or StackedInline (vertical layout, just like the default model layout). You can add the BookInstance information inline to our Book detail by adding the lines below in bold near your BookAdmin:

- -
class BooksInstanceInline(admin.TabularInline):
-    model = BookInstance
-
-@admin.register(Book)
-class BookAdmin(admin.ModelAdmin):
-    list_display = ('title', 'author', 'display_genre')
-    inlines = [BooksInstanceInline]
-
- -

Now navigate to a view for a Book in your website — at the bottom you should now see the book instances relating to this book (immediately below the book's genre fields):

- -

Admin Site - Book with Inlines

- -

In this case all we've done is declare our tabular inline class, which just adds all fields from the inlined model. You can specify all sorts of additional information for the layout, including the fields to display, their order, whether they are read only or not, etc. (see TabularInline for more information).

- -
-

Note: There are some painful limits in this functionality! In the screenshot above we have three existing book instances, followed by three placeholders for new book instances (which look very similar!). It would be better to have NO spare book instances by default and just add them with the Add another Book instance link, or to be able to just list the BookInstances as non-readable links from here. The first option can be done by setting the extra attribute to 0 in BooksInstanceInline model, try it by yourself.

-
- -

自我挑戰

- -

在本節中我們學到了很多東西,所以現在該您嘗試一些事情了。

- -
    -
  1. 對於BookInstance列表視圖(list view),添加代碼以顯示booksstatusdue back dateid(而不是默認的__str __()文本)。
  2. -
  3. 使用與Book/BookInstance相同的方法將Book項目的內聯列表添加到Author 的詳細視圖(detail view)中。
  4. -
- - - -

小結

- -

就是這樣! 您現在已經了解瞭如何以最簡單和改進的形式設置管理者網站,如何創建超級用戶,以及如何瀏覽管理者網站,查看,刪除和更新記錄。 在此過程中,您已經創建了許多Books,BookInstances,Genres和Authors,一旦我們創建了自己的view和templates,便可以列出和顯示這些記錄。

- -

延伸閱讀

- - - -

{{PreviousMenuNext("Learn/Server-side/Django/Models", "Learn/Server-side/Django/Home_page", "Learn/Server-side/Django")}}

- -

In this module

- - diff --git a/files/zh-tw/learn/server-side/django/admin_site/index.md b/files/zh-tw/learn/server-side/django/admin_site/index.md new file mode 100644 index 00000000000000..98f90a41e96751 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/admin_site/index.md @@ -0,0 +1,355 @@ +--- +title: 'Django Tutorial Part 4: Django admin site' +slug: Learn/Server-side/Django/Admin_site +translation_of: Learn/Server-side/Django/Admin_site +--- +{{LearnSidebar}}{{PreviousMenuNext("Learn/Server-side/Django/Models", "Learn/Server-side/Django/Home_page", "Learn/Server-side/Django")}} + +現在,我們已經為本地圖書館網站 [LocalLibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) 創建了模型,我們接下來使用 Django 管理網站,去添加 一些 “真實的“ 書本數據。首先,我們展示如何用管理網站註冊模型,然後展示如何登錄和創建一些數據。本文最後,我們介紹可以進一步改進管理網站的建議。 + + + + + + + + + + + + +
前提: + 先完成: + Django Tutorial Part 3: Using models. +
目標: +

+ 了解 Django 管理站的優點與侷限,並使用它來為我們的模型新增一些資料。 +

+
+ +## 概覽 + +Django 管理應用程序可以使用您的模型,自動構建可用於創建,查看,更新和刪除記錄的網站區域。這可以在開發過程中,節省大量的時間,從而很容易測試您的模型,並了解您是否擁有正確的數據。根據網站的類型,管理應用程序也可用於管理生產中的數據。 Django 項目建議僅用於內部數據管理(即僅供管理員或組織內部人員使用),因為以模型為中心的方法,不一定是所有用戶最好的界面,並且暴露了大量不必要的關於模型的細節。 + +創建基礎項目時,自動完成所有的配置文件,包含您的網站中的管理應用程序在內(有關所需實際依賴關係的信息,如有需要請看 [Django docs here](https://docs.djangoproject.com/en/2.0/ref/contrib/admin/))。其結果是,要將模型添加到管理應用程序,你必須做的,僅僅是註冊他們。在本文末尾,我們將簡要介紹,如何進一步配置管理區域,以更好地顯示我們的模型數據。 + +註冊模型後,我們將展示,如何創建一個新的 “超級用戶”,登錄到該網站,並創建一些書籍,作者,書籍實例和書籍類別。這些將有助於測試我們將在下一個教程中,開始創建的視圖和模板。 + +## 註冊模型(Registering models ) + +首先,我們從 catalog app 中打開 **admin.py** (**/locallibrary/catalog/admin.py**),目前它長的像下面區塊,注意它已經幫你導入 `django.contrib.admin`: + +```python +from django.contrib import admin + +# Register your models here. +``` + +將下方的程式碼複製貼在 **admin.py** 文件下方以註冊所有模型,這段程式碼簡單來說就是先將模型導入,再呼叫 `admin.site.register` 函式來註冊每個模型。 + +```python +from .models import Author, Genre, Book, BookInstance + +admin.site.register(Book) +admin.site.register(Author) +admin.site.register(Genre) +admin.site.register(BookInstance) +``` + +> **備註:** 如果你在上一章節最後有接受挑戰並建立一個書本的「語言模型」 ([查看模型教學文章](/zh-TW/docs/Learn/Server-side/Django/Models)),你必需也要導入並註冊該模型! + +這是**註冊模型**最簡單的方式。 + +而管理站則是高度用戶化的,我們會在接下來繼續說明其它註冊你的模型的方式。 + +## 創建超級用戶(Creating a superuser) + +為了能夠登入管理站,我們需要一個有啟用員工狀態(_Staff_ status)的使用者帳號,另外為了要能檢視與產生資料,我們也需要讓這個使用者帳號擁有管理所有物件的權限,因此,你可以透過 **manage.py** 來創建一個擁有所有網站存取權限的超級用戶(superuser)。 + +在與 **manage.py** 同一個資料夾中執行下方指令,建立一個超級用戶,你會被提示要輸入「使用者名稱」、「使用者 e-mail」和「強度夠高的密碼」。 + +```bash +python3 manage.py createsuperuser +``` + +當完成指令輸入後,一個新的超級用戶就會被加進資料庫中,再來只要重新啟動開發用 server ,你便可以進行登入測試: + +```bash +python3 manage.py runserver +``` + +## 登入並開始使用網站 + +要登入網站,必須先連上 _/admin_ URL (e.g. [http://127.0.0.1:8000/admin](http://127.0.0.1:8000/admin/)) 並且輸入你的超級用戶的使用者名稱與密碼(你會被重新導向登入頁面,輸入你的帳密後會再回到 _/admin_ URL)。 + +網站中的這部分羅列了所有以我們安裝的 app 分組的模型,你可以點擊模型名稱進入陳列所有與其相關連資料的頁面,而你可以進一步編輯它們,或者你也可以直接點擊模型名稱旁邊的 **Add** 連結來開始創建該類型的資料。 + +![Admin Site - Home page](admin_home.png) + +點擊 Books 右邊的 **Add** 連結來新增一本新書(會產生如下方的對話方塊),可以去觀察每個字段(field)、小部件、提示文字(如果有的話)是如何對應到你的模型的。 + +在字段中輸入值,你可以透過各個字段旁邊的 **+** 按鈕來新增「作者」或「書籍類別」(或者從列表中選擇你已經新增的值),當你完成後可以點選 **SAVE**, **Save and add another**, 或 **Save and continue editing** 來儲存該筆資料。 + +![Admin Site - Book Add](admin_book_add.png) + +> **備註:** 在這邊我們希望你花點時間在你的 app 中新增一些書本、作者和書及類型(例如:奇幻等)。請確保每位作者與每種書籍類型都分別關聯了一本以上的書(這在文章稍後的實作的時候,會讓你的列表與細節視圖更加豐富有趣)。 + +當你新增完書本後,點擊上方書籤的 **Home** 連結回到主要管理頁面,接著點擊 **Books** 連結來展示目前的書本清單(你也可以點及其他連結看看其他模型的列表),現在你已經加了幾本書,畫面應該會與下方截圖類似,你可以看到下方陳列了每本書的標題,這是我們在上一篇文章所提到的 Book 模型中的 `__str__()` 方法所回傳的值。 + +![Admin Site - List of book objects](admin_book_list.png) + +在列表中,如果要刪掉你不想要的書,只需要先勾選欲刪除書本的勾選方框,從動作下拉選單選擇刪除動作(delete action),接著點選 **GO** 按鈕即可,另外你也可以點選 **ADD BOOK** 按鈕來新增一本書。 + +你可以點擊書名來編輯它,下方顯示的書本編輯頁面幾乎與 **Add** 頁面相同,主要差異在於頁面的標題(Change book)以及增加了 **Delete**, **HISTORY** 和 **VIEW ON SITE** 按鈕(會有這個按鈕出現是因為我們之前在模型中有定義了 `get_absolute_url()` 的方法) + +![Admin Site - Book Edit](admin_book_modify.png) + +現在透過頁面上方的索引連結回到 **Home** 頁面,然後看看 **Author** 和 **Genre** 列表,你在新增書本的時候應該已經新增了一些資料,不過你還可以再新增更多。 + +你還沒有任何書本實例(Book Instances),因為這不會在建立書本時就產生(但你可以在新增 `BookInstance` 資料時新增 `Book` ,這是 `ForeignKey` 字段的性質)。現在回到 Home 頁面然後點擊 Book instances 的 **Add** 按鈕,畫面會呈現如下圖的頁面,注意第一列有個很長、全域唯一的 id 編碼,它可以用來區分每本書在圖書館裡的每個副本。 + +![Admin Site - BookInstance Add](admin_bookinstance_add.png) + +幫你的每本書都新增幾筆不同的資料,有些資料的狀態(Status)請設成 _Available ,有些則設成 On loan,如果狀態為_ **not** _Available,那記得需要設定到期日(Due back_ date*)。* + +就是這樣!你現在已經學會了如何建立與使用管理站(administration site),你也為你的 `Book`, `BookInstance`, `Genre`, 和 `Author` 模型建立了幾筆資料,再來當我們建立好視圖(Views)以及模板(Templates)後,就會開始來使用它們。 + +## 進階組態(Advanced configuration) + +Django 在「透過註冊模型的資訊建立管理站」這方面做得非常好: + +- 每個模型都有各自的資料列表,每筆資料都藉由模型的 `__str__()` 方法來做分辨,而且會連結到更詳細的視圖/表格以便後續編輯,而且在預設情況下,這個視圖(View)的上方有一個「動作清單(action menu)」,你可以使用裡面的 delete 功能來執行資料的刪除作業。 +- 用於編輯和新增紀錄的模型詳細紀錄表單包含了模型中的所有字段,並依照宣告順序垂直排列。 + +你可以進一步訂製介面讓它更好用,以下是你可以進一步做的: + +- 列表視圖(List views): + + - 為每一筆紀錄增加額外的字段/資訊陳列。 + - 為這些紀錄列表增加篩選器(例如:使用日期、使用狀態進行過濾) + - 為動作選單(action menu)添加額外的動作,並選擇是否要讓此選單在表格中呈現。 + +- 細節視圖(Detail views): + + - 選擇那些字段要隨著「順序、分組、可否編輯、是否被模組使用、取向」而陳列(或排除)。 + - 添加相關的字段來允許內聯編輯(inline editing)(例如:添加一個功能讓你可以在新增一個作者的時候也順便能夠新增或編輯他的書本記錄)。 + +這部分我們將要來看幾個有助於改善 _LocalLibrary 介面的小變化,包含了添加更多資訊到_ `Book` 和 `Author` 模型列表,以及改善編輯視圖的排版。我們不會改變 `Language` 和 `Genre` 的模型外貌因為他們都各只有 1 個字段,這樣做沒好處! + +你可以在 [The Django Admin site](https://docs.djangoproject.com/en/2.0/ref/contrib/admin/) (Django Docs) 找到關於管理站訂製選擇的完整參考。 + +### 註冊一個 模型管理 類別 (ModelAdmin class) + +為了要改變模型在管理站的陳列方式,你需要定義一個模型管理([ModelAdmin](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-objects))類別 (他是用來描述排版的),並且將它與其他模型一起註冊。 + +我們現在先從 `Author` 模型開始。打開 catalog app 中的 **admin.py** 檔案(**/locallibrary/catalog/admin.py**),並將先前註冊 `Author` 模型的程式碼註解(在程式碼前面加一個 # 前綴): + +```js +# admin.site.register(Author) +``` + +現在加上一個新的 `AuthorAdmin` 類別與註冊函式,如下方所示: + +```python +# Define the admin class +class AuthorAdmin(admin.ModelAdmin): + pass + +# Register the admin class with the associated model +admin.site.register(Author, AuthorAdmin) +``` + +現在我們要為 `Book` 以及 `BookInstance` 模型添加 `ModelAdmin` 類別,我們一樣要先把原本的註冊程式碼註解: + +```js +#admin.site.register(Book) +#admin.site.register(BookInstance) +``` + +現在我們要創造並註冊新的模型;為了達到示範的目的,我們會使用 `@register` 裝飾器替代先前做法來註冊模型(這跟 `admin.site.register()` 的語法做的事情完全一樣): + +```python +# Register the Admin classes for Book using the decorator +@admin.register(Book) +class BookAdmin(admin.ModelAdmin): + pass + +# Register the Admin classes for BookInstance using the decorator +@admin.register(BookInstance) +class BookInstanceAdmin(admin.ModelAdmin): + pass +``` + +目前為止我們的管理類別都是空的(可以看到 "`pass"`),所以我們的管理行為都不會改變!現在我們可以來進一步定義我們的「特定模型的管理行為」。 + +### 配置列表視圖(Configure list views) + +我們的 _LocalLibrary 目前條列出所有作者,而他們都是使用以模型的_ `__str__()` _方法產生的物件名稱。如過你只有少數幾個作者,那倒還好,但如果作者很多,你最後可能會有非常多副本。因此為了區別他們,或者你只是想呈現更多作者的有趣訊息,你可以使用「列表展示」(_[list_display](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display)_)來位視圖添加額外的字段。_ + +將你的 `AuthorAdmin` 類別以下方程式碼取代。下方程式碼可以看出來,列表中被展示出來的字段名稱會被以需要的排序宣告為元組(tuple)形式。 + +```python +class AuthorAdmin(admin.ModelAdmin): + list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death') +``` + +現在把網站導向作者列表,上方所設定的字段應該會被陳列出來,如下: + +![Admin Site - Improved Author List](admin_improved_author_list.png) + +至於我們的 `Book` 模型,我們將額外添加 `author` 和 `genre` 兩樣。`author` 是一個`ForeignKey` 外鍵字段(一對一)關係,因此他將會透過關聯紀錄的 `__str__()` 值來表示。 + +將 `BookAdmin` 類別以下方區段程式碼取代: + +```python +class BookAdmin(admin.ModelAdmin): + list_display = ('title', 'author', 'display_genre') +``` + +很不幸地,我們無法直接在 `list_display` 中指定「書籍類別」(genre field)字段,因為它是一個 `ManyToManyField` (多對多字段),因為如果這樣做會造成很大的資料庫讀寫「成本」,所以 Django 會預防這樣的狀況發生,因此,取而代之,我們將定義一個 `display_genre` 函式以「字串」形式得到書籍類別。(下方有定義此函式) + +> **備註:** Getting the `genre` may not be a good idea here, because of the "cost" of the database operation. We're showing you how because calling functions in your models can be very useful for other reasons — for example to add a _Delete_ link next to every item in the list. + +將以下程式碼添加到`Book`模型(**models.py**)。 這會從`genre`記錄的的頭三個值(如果有的話)創建一個字符串, 和創建一個在管理者網站中出現的`short_description`標題。 + +```python + def display_genre(self): + """Create a string for the Genre. This is required to display genre in Admin.""" + return ', '.join(genre.name for genre in self.genre.all()[:3]) + + display_genre.short_description = 'Genre' +``` + +保存模型並更新管理員後,打開您的網站並轉到“Books”列表頁面; 您應該會看到類似以下的書籍清單: + +![Admin Site - Improved Book List](admin_improved_book_list.png) + +`Genre` 模型(如果定義了語言模型,則還有 `Language` 模型)都有一個欄位,因此沒有必要為它們創建其他模型以顯示欄位。 + +> **備註:** 更新 `BookInstance` 模型列表用來顯示狀態和預期的返回日期是有價值的。 我們在本文結尾處添加了一個挑戰! + +### 加入列表過濾器 (List Filter) + +當你的列表有很多個記錄時, 加入列表過濾器可以幫助你過濾想顯示的記錄。加入`list_filter`這個屬性就可以。請用以下的程式碼來取代原本的 `BookInstanceAdmin` 類別 + +```python +class BookInstanceAdmin(admin.ModelAdmin): + list_filter = ('status', 'due_back') +``` + +現在的列表視圖右邊會多了一個過濾器。你可以選擇 dates 和 status 來做過濾: + +![Admin Site - BookInstance List Filters](admin_improved_bookinstance_list_filters.png) + +### 組織詳細視圖佈局 + +默認情況下,局部視圖按照模型中聲明的順序垂直排列所有字段。 您可以更改聲明的順序,顯示(或排除)哪些字段,使用分段來組織資訊,水平顯示還是垂直顯示字段,甚至管理表單中使用哪些編輯小部件。 + +> **備註:** _LocalLibrary_ 模型相對簡單,因此我們無須更改佈局。 但我們仍然會進行一些更改,向您展示如何進行。 + +#### 控制那些欄位顯示並佈置 + +更新你的 `AuthorAdmin` 類別用來新增 `fields` 這行,如同下列所示 (粗體): + +```python +class AuthorAdmin(admin.ModelAdmin): + list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death') + fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death')] +``` + +`fields` 屬性僅按順序列出了要在表單上顯示的那些欄位。 默認情況下,字段是垂直顯示的,但是如果您進一步將它們分組到一個元組中,它們將水平顯示(如上面的“日期”字段中所示)。 + +在您的網站上,轉到作者詳細信息視圖-現在應如下所示: + +![Admin Site - Improved Author Detail](admin_improved_author_detail.png) + +> **備註:** 您還可以使用 `exclude` 屬性來聲明要從表單中排除的屬性列表(將顯示模型中的所有其他屬性)。 + +#### Sectioning the detail view + +You can add "sections" to group related model information within the detail form, using the [fieldsets](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.fieldsets) attribute. + +In the `BookInstance` model we have information related to what the book is (i.e. `name`, `imprint`, and `id`) and when it will be available (`status`, `due_back`). We can add these in different sections by adding the text in bold to our `BookInstanceAdmin` class. + +```python +@admin.register(BookInstance) +class BookInstanceAdmin(admin.ModelAdmin): + list_filter = ('status', 'due_back') + + fieldsets = ( + (None, { + 'fields': ('book', 'imprint', 'id') + }), + ('Availability', { + 'fields': ('status', 'due_back') + }), + ) +``` + +Each section has its own title (or `None`, if you don't want a title) and an associated tuple of fields in a dictionary — the format is complicated to describe, but fairly easy to understand if you look at the code fragment immediately above. + +Now navigate to a book instance view in your website; the form should appear as shown below: + +![Admin Site - Improved BookInstance Detail with sections](admin_improved_bookinstance_detail_sections.png) + +### Inline editing of associated records + +Sometimes it can make sense to be able to add associated records at the same time. For example, it may make sense to have both the book information and information about the specific copies you've got on the same detail page. + +You can do this by declaring [inlines](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.inlines), of type [TabularInline](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.TabularInline) (horizonal layout) or [StackedInline](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.StackedInline) (vertical layout, just like the default model layout). You can add the `BookInstance` information inline to our `Book` detail by adding the lines below in bold near your `BookAdmin`: + +```python +class BooksInstanceInline(admin.TabularInline): + model = BookInstance + +@admin.register(Book) +class BookAdmin(admin.ModelAdmin): + list_display = ('title', 'author', 'display_genre') + inlines = [BooksInstanceInline] +``` + +Now navigate to a view for a `Book` in your website — at the bottom you should now see the book instances relating to this book (immediately below the book's genre fields): + +![Admin Site - Book with Inlines](admin_improved_book_detail_inlines.png) + +In this case all we've done is declare our tabular inline class, which just adds all fields from the _inlined_ model. You can specify all sorts of additional information for the layout, including the fields to display, their order, whether they are read only or not, etc. (see [TabularInline](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.TabularInline) for more information). + +> **備註:** There are some painful limits in this functionality! In the screenshot above we have three existing book instances, followed by three placeholders for new book instances (which look very similar!). It would be better to have NO spare book instances by default and just add them with the **Add another Book instance** link, or to be able to just list the `BookInstance`s as non-readable links from here. The first option can be done by setting the `extra` attribute to 0 in `BooksInstanceInline` model, try it by yourself. + +## 自我挑戰 + +在本節中我們學到了很多東西,所以現在該您嘗試一些事情了。 + +1. 對於`BookInstance`列表視圖(list view),添加代碼以顯示`books`,`status`,`due back date` 和 `id`(而不是默認的\_\_str \_\_()文本)。 +2. 使用與`Book/BookInstance`相同的方法將`Book`項目的內聯列表添加到`Author` 的詳細視圖(detail view)中。 + +## 小結 + +就是這樣! 您現在已經了解瞭如何以最簡單和改進的形式設置管理者網站,如何創建超級用戶,以及如何瀏覽管理者網站,查看,刪除和更新記錄。 在此過程中,您已經創建了許多 Books,BookInstances,Genres 和 Authors,一旦我們創建了自己的 view 和 templates,便可以列出和顯示這些記錄。 + +## 延伸閱讀 + +- [Writing your first Django app, part 2: Introducing the Django Admin](https://docs.djangoproject.com/en/2.0/intro/tutorial02/#introducing-the-django-admin) (Django docs) +- [The Django Admin site](https://docs.djangoproject.com/en/2.0/ref/contrib/admin/) (Django Docs) + +{{PreviousMenuNext("Learn/Server-side/Django/Models", "Learn/Server-side/Django/Home_page", "Learn/Server-side/Django")}} + +## In this module + +- [Django introduction](/en-US/docs/Learn/Server-side/Django/Introduction) +- [Setting up a Django development environment](/en-US/docs/Learn/Server-side/Django/development_environment) +- [Django Tutorial: The Local Library website](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django Tutorial Part 2: Creating a skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) +- [Django Tutorial Part 3: Using models](/en-US/docs/Learn/Server-side/Django/Models) +- [Django Tutorial Part 4: Django admin site](/en-US/docs/Learn/Server-side/Django/Admin_site) +- [Django Tutorial Part 5: Creating our home page](/en-US/docs/Learn/Server-side/Django/Home_page) +- [Django Tutorial Part 6: Generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views) +- [Django Tutorial Part 7: Sessions framework](/en-US/docs/Learn/Server-side/Django/Sessions) +- [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/Authentication) +- [Django Tutorial Part 9: Working with forms](/en-US/docs/Learn/Server-side/Django/Forms) +- [Django Tutorial Part 10: Testing a Django web application](/en-US/docs/Learn/Server-side/Django/Testing) +- [Django Tutorial Part 11: Deploying Django to production](/en-US/docs/Learn/Server-side/Django/Deployment) +- [Django web application security](/en-US/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django mini blog](/en-US/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/authentication/index.html b/files/zh-tw/learn/server-side/django/authentication/index.html deleted file mode 100644 index 008333063f3902..00000000000000 --- a/files/zh-tw/learn/server-side/django/authentication/index.html +++ /dev/null @@ -1,698 +0,0 @@ ---- -title: 'Django Tutorial Part 8: User authentication and permissions' -slug: Learn/Server-side/Django/Authentication -translation_of: Learn/Server-side/Django/Authentication ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Django/Sessions", "Learn/Server-side/Django/Forms", "Learn/Server-side/Django")}}
- -

在本教程中,我們將會展示如何允許用戶使用自己的帳戶登入到您的網站,以及如何根據用戶是否已登入和權限的不同來控制他們可以執行和查看的內容。作為展示的一部分,我們會擴展 LocalLibrary 網站,添加登入頁面和登出頁面,以及用來查看已借閱的圖書的頁面 - 分為用戶與員工兩種不同頁面。

- - - - - - - - - - - - -
前提:完成至 Django 線上教學 7: 會話(Sessions)框架為止的所有主題。
目標:了解如何設定與運用使用者驗證與權限機制。
- -

大綱

- -

Django提供認證和授權(“ permission”)系統,該系統建立在上一教程中討論的會話框架的基礎上。透過它可以驗證用戶憑證並定義個別用戶能夠執行的操作。 該框架包括用於UsersGroups 的內置模型(一般常用來一次性套用權限於一群用戶上的方式),用於指定用戶是否可以執行任務的權限/旗標,用於登入用戶的表單和視圖,以及 查看用於限制內容的工具。

- -
-

注意: 從Django角度而言,身份驗證系統需要做到非常通用,因此不提供其他網頁身份驗證系統中提供的某些功能。 需要解決一些常見問題的話可以透過第三方軟件包。 例如,限制登錄嘗試和透過第三方進行身份驗證(例如OAuth)。

-
- -

在本教程中,我們將會展示如何在LocalLibrary網站中啟用用戶身份驗證,並建立自己的登入和登出頁面,為模型添加權限以及控制對頁面的訪問。 我們將根據身份驗證/權限顯示為用戶或是圖書館員設計的已借出書籍列表。

- -

身份驗證系統非常有彈性,您可以根據需要從頭開始構建URL,表單,視圖和模板,只透過提供的API來登入用戶。 但是,在本文中,我們將為登入與登出頁面使用Django的“ stock”身份驗證視圖和表單。 我們仍然需要建立一些模板,但這很簡單。

- -

我們還將向您展示如何建立權限,並在視圖和模板中檢查登入狀態和權限。

- -

Enabling authentication

- -

當我們創建框架網站時(在教程2中),身份驗證已自動啟用,因此您此時無需執行任何其他操作。

- -
-

注意: 當我們使用django-admin startproject命令創建應用程序時,所有必要的配置都為我們完成了。 用戶和模型權限的數據庫表是在我們首次調用python manage.py migrate時創建的。

-
- -

該配置是在項目文件(locallibrary/locallibrary/settings.py)的INSTALLED_APPSMIDDLEWARE 部分中設置的,如下所示:

- -
INSTALLED_APPS = [
-    ...
-    'django.contrib.auth',  #Core authentication framework and its default models.
-    'django.contrib.contenttypes',  #Django content type system (allows permissions to be associated with models).
-    ....
-
-MIDDLEWARE = [
-    ...
-    'django.contrib.sessions.middleware.SessionMiddleware',  #Manages sessions across requests
-    ...
-    'django.contrib.auth.middleware.AuthenticationMiddleware',  #Associates users with requests using sessions.
-    ....
-
- -

Creating users and groups

- -

當我們在教程4中查看Django管理站點時,您已經創建了第一個用戶(這是一個超級用戶,使用命令ppython manage.py createsuperuser創建)。 我們的超級用戶已經通過身份驗證,並且具有所有權限,因此我們需要創建一個測試用戶來代表普通站點用戶。 我們將使用管理站點來創建本地圖書館組和網站登錄名,因為這是最快的方法之一。

- -
-

注意: 您還可以通過編程方式創建用戶,如下所示。 例如,如果要開發一個界面以允許用戶創建自己的登錄名,則必須這樣做(您不應授予用戶訪問管理站點的權限)。

- -
from django.contrib.auth.models import User
-
-# Create user and save to the database
-user = User.objects.create_user('myusername', 'myemail@crazymail.com', 'mypassword')
-
-# Update fields and then save again
-user.first_name = 'John'
-user.last_name = 'Citizen'
-user.save()
-
-
- -

在下面,我們將首先創建一個組,然後創建一個用戶。 即使我們還沒有添加庫成員的任何權限,但是如果以後需要添加,將它們一次添加到組中要比分別添加到每個成員要容易得多。

- -

啟動開發服務器,然後在本地Web瀏覽器(http://127.0.0.1:8000/admin/)中導航到管理站點。 使用您的超級用戶帳戶的憑據登錄到該站點。 管理站點的頂層顯示所有模型,按“ django應用程序”排序。 在“Authentication and Authorisation”部分,您可以單擊UsersGroups鏈接以查看其現有記錄。

- -

Admin site - add groups or users

- -

首先,讓我們為圖書館成員創建一個新組。

- -
    -
  1. 單擊Add按鈕(在組旁邊)以創建一個新組; 輸入該組的名稱“Library Members”。
    - Admin site - add group
  2. -
  3. 我們不需要該組的任何權限,因此只需按SAVE (您將被帶到組列表)。
  4. -
- -

現在讓我們創建一個用戶:

- -
    -
  1. 導航回到管理站點的主頁
  2. -
  3. 單擊“用戶”旁邊的“添加”按鈕以打開“添加用戶”對話框。
    - Admin site - add user pt1
  4. -
  5. 輸入適合您的測試用戶的用戶名和密碼/密碼確認
  6. -
  7. SAVE創建用戶。
    - 管理站點將創建新用戶,並立即將您帶到“更改用戶”視窗,您可以在其中更改用戶名並為用戶模型的可選字段添加信息。 這些字段包括名字,姓氏,電子郵件地址,用戶狀態和權限(僅應設置“活動”標誌)。 在更下方的位置,您可以指定用戶的組和權限,並查看與該用戶相關的重要日期(例如,他們的加入日期和上次登錄日期)。
    - Admin site - add user pt2
  8. -
  9. 在“組”部分中,從“可用組”列表中選擇“Library Member”組,然後按框之間的右箭頭將其移至“選擇的組”框中。Admin site - add user to group
  10. -
  11. 我們在這裡不需要執行任何其他操作,因此只需再次選擇SAVE 即可進入用戶列表。
  12. -
- -

就是這樣而已! 現在,您將擁有一個“普通庫成員”帳戶,您將可以使用該帳戶進行測試(一旦我們實現了頁面以使其能夠登錄)。

- -
-

注意:您應該嘗試創建另一個庫成員用戶。 另外,為圖書館員創建一個組,並為其添加用戶!

-
- -

Setting up your authentication views

- -

Django提供了創建身份驗證頁面所需的幾乎所有內容,以處理“開箱即用”的登錄,註銷和密碼管理。 這包括URL映射器,視圖和表單,但不包括模板-我們必須創建自己的模板!

- -

在本節中,我們顯示如何將默認系統集成到LocalLibrary網站中並創建模板。 我們將它們放在主項目URL中。

- -
-

注意: 您不必使用任何代碼,但是您可能想要使用它,因為它使事情變得容易得多。 如果您更改用戶模型(一個高級主題!),幾乎可以肯定需要更改表單處理代碼,但是即使如此,您仍然可以使用庫存視圖功能。

-
- -
-

注意: 在這種情況下,我們可以合理地將身份驗證頁面(包括URL和模板)放入目錄應用程序中。 但是,如果我們有多個應用程序,最好將這種共享的登錄行為分開,並使其在整個站點中都可用,這就是我們在此處顯示的內容!

-
- -

Project URLs

- -

將以下內容添加到項目urls.py文件(locallibrary/locallibrary/urls.py)文件的底部:

- -
#Add Django site authentication urls (for login, logout, password management)
-urlpatterns += [
-    path('accounts/', include('django.contrib.auth.urls')),
-]
-
- -

導航到http://127.0.0.1:8000/accounts/ URL(注意尾隨斜杠!),然後Django將顯示一個錯誤,指出找不到此URL,並列出了它嘗試的所有URL。 從中您可以看到將起作用的URL,例如:

- -
-

注意: 使用上述方法會在方括號中添加以下網址,這些網址可用於反轉網址映射。 您無需執行其他任何操作-上面的url映射會自動映射以下提到的URL。

-
- -
-
accounts/ login/ [name='login']
-accounts/ logout/ [name='logout']
-accounts/ password_change/ [name='password_change']
-accounts/ password_change/done/ [name='password_change_done']
-accounts/ password_reset/ [name='password_reset']
-accounts/ password_reset/done/ [name='password_reset_done']
-accounts/ reset/<uidb64>/<token>/ [name='password_reset_confirm']
-accounts/ reset/done/ [name='password_reset_complete']
-
- -

現在嘗試導航到登錄URL(http://127.0.0.1:8000/accounts/login/)。 這將再次失敗,但是會顯示一條錯誤消息,告訴您我們在模板搜索路徑上缺少必需的模板(registration/login.html)。 您會在頂部黃色部分看到以下幾行:

- -
Exception Type:    TemplateDoesNotExist
-Exception Value:    registration/login.html
- -

下一步是在搜索路徑上創建註冊目錄,然後添加login.html文件。

- -

Template directory

- -

我們剛剛添加的url(和隱式視圖)期望在模板搜索路徑中某個目錄/registration/ 中找到它們的關聯模板。

- -

對於這個網站,我們將HTML頁面放在templates/registration/目錄中。 此目錄應位於您的項目根目錄中,即與cataloglocallibrary 文件夾相同的目錄中)。 請立即創建這些文件夾。

- -
-

Note: Your folder structure should now look like the below:
- locallibrary (django project folder)
- |_catalog
- |_locallibrary
- |_templates (new)
- |_registration

-
- -

為了使這些目錄對模板加載器可見(即將該目錄放置在模板搜索路徑中),請打開項目設置(/locallibrary/locallibrary/settings.py),並更新TEMPLATES 部分的DIRS行,如圖所示。

- -
TEMPLATES = [
-    {
-        ...
-        'DIRS': ['./templates',],
-        'APP_DIRS': True,
-        ...
-
- -

Login template

- -
-

重要信息:本文提供的身份驗證模板是Django演示登錄模板的非常基本/稍作修改的版本。 您可能需要自定義它們以供自己使用!

-
- -

創建一個名為/locallibrary/templates/registration/login.html的新HTML文件。 為其提供以下內容:

- -
{% extends "base_generic.html" %}
-
-{% block content %}
-
-{% if form.errors %}
-  <p>Your username and password didn't match. Please try again.</p>
-{% endif %}
-
-{% if next %}
-  {% if user.is_authenticated %}
-    <p>Your account doesn't have access to this page. To proceed,
-    please login with an account that has access.</p>
-  {% else %}
-    <p>Please login to see this page.</p>
-  {% endif %}
-{% endif %}
-
-<form method="post" action="{% url 'login' %}">
-{% csrf_token %}
-
-<div>
-  <td>\{{ form.username.label_tag }}</td>
-  <td>\{{ form.username }}</td>
-</div>
-<div>
-  <td>\{{ form.password.label_tag }}</td>
-  <td>\{{ form.password }}</td>
-</div>
-
-<div>
-  <input type="submit" value="login" />
-  <input type="hidden" name="next" value="\{{ next }}" />
-</div>
-</form>
-
-{# Assumes you setup the password_reset view in your URLconf #}
-<p><a href="{% url 'password_reset' %}">Lost password?</a></p>
-
-{% endblock %}
- -

該模板與我們之前看到的模板有一些相似之處-它擴展了我們的基本模板並覆蓋了內容塊。 其餘代碼是相當標準的表單處理代碼,我們將在以後的教程中進行討論。 現在您只需要知道的是,這將顯示一個表格,您可以在其中輸入用戶名和密碼,並且如果輸入無效的值,則在頁面刷新時會提示您輸入正確的值。

- -

保存模板後,導航回到登錄頁面(http://127.0.0.1:8000/accounts/login/),您應該看到類似以下內容:

- -

Library login page v1

- -

如果嘗試登錄將成功,並且您將被重定向到另一個頁面(默認情況下為http://127.0.0.1:8000/accounts/profile/)。 這裡的問題是,默認情況下,Django期望登錄後將您帶到個人資料頁面,情況可能與否。 由於您尚未定義此頁面,因此會出現另一個錯誤!

- -

打開項目設置(/locallibrary/locallibrary/settings.py) ,然後將下面的文本添加到底部。 現在,當您登錄時,默認情況下應將您重定向到網站主頁。

- -
# Redirect to home URL after login (Default redirects to /accounts/profile/)
-LOGIN_REDIRECT_URL = '/'
-
- -

Logout template

- -

如果您導航到登出URL (http://127.0.0.1:8000/accounts/logout/) ,則會看到一些奇怪的行為-您的用戶將被確定地註銷,但是您將被帶到Admin 註銷頁面。 那不是您想要的,僅僅是因為該頁面上的登錄鏈接將您帶到Admin 登錄屏幕(並且僅對具有is_staff 權限的用戶可用)。

- -

創建並打開 /locallibrary/templates/registration/logged_out.html。 複製以下文本:

- -
{% extends "base_generic.html" %}
-
-{% block content %}
-  <p>Logged out!</p>
-  <a href="{% url 'login'%}">Click here to login again.</a>
-{% endblock %}
- -

這個模板非常簡單。 它僅顯示一條消息,通知您已註銷,並提供一個鏈接,您可以按此鏈接返回登錄屏幕。 如果再次進入註銷URL,您應該看到以下頁面:

- -

Library logout page v1

- -

Password reset templates

- -

默認的密碼重置系統使用電子郵件向用戶發送重置鏈接。 您需要創建表格以獲取用戶的電子郵件地址,發送電子郵件,允許他們輸入新密碼並在整個過程完成時註明。

- -

以下模板可以用作起點。

- -

密碼重設表格

- -

這是用於獲取用戶電子郵件地址(用於發送密碼重置電子郵件)的表格。 創建/locallibrary/templates/registration/password_reset_form.html,並為其提供以下內容:

- -
{% extends "base_generic.html" %}
-
-{% block content %}
-  <form action="" method="post">
-  {% csrf_token %}
-  {% if form.email.errors %}
-    {{ form.email.errors }}
-  {% endif %}
-      <p>\{{ form.email }}</p>
-    <input type="submit" class="btn btn-default btn-lg" value="Reset password">
-  </form>
-{% endblock %}
-
- -

密碼重置完成

- -

收集您的電子郵件地址後,將顯示此表單。創建 /locallibrary/templates/registration/password_reset_done.html,並為其提供以下內容:

- -
{% extends "base_generic.html" %}
-
-{% block content %}
-  <p>We've emailed you instructions for setting your password. If they haven't arrived in a few minutes, check your spam folder.</p>
-{% endblock %}
-
- -

密碼重置電子郵件

- -

該模板提供了HTML電子郵件的文本,其中包含我們將發送給用戶的重置鏈接。 創建/locallibrary/templates/registration/password_reset_email.html,並為其提供以下內容:

- -
Someone asked for password reset for email \{{ email }}. Follow the link below:
-\{{ protocol}}://\{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
-
- -

密碼重置確認

- -

單擊密碼重置電子郵件中的鏈接後,即可在此頁面輸入新密碼。 創建 /locallibrary/templates/registration/password_reset_confirm.html,並為其提供以下內容:

- -
{% extends "base_generic.html" %}
-
-{% block content %}
-    {% if validlink %}
-        <p>Please enter (and confirm) your new password.</p>
-        <form action="" method="post">
-            <div style="display:none">
-                <input type="hidden" value="\{{ csrf_token }}" name="csrfmiddlewaretoken">
-            </div>
-            <table>
-                <tr>
-                    <td>\{{ form.new_password1.errors }}
-                        <label for="id_new_password1">New password:</label></td>
-                    <td>\{{ form.new_password1 }}</td>
-                </tr>
-                <tr>
-                    <td>\{{ form.new_password2.errors }}
-                        <label for="id_new_password2">Confirm password:</label></td>
-                    <td>\{{ form.new_password2 }}</td>
-                </tr>
-                <tr>
-                    <td></td>
-                    <td><input type="submit" value="Change my password" /></td>
-                </tr>
-            </table>
-        </form>
-    {% else %}
-        <h1>Password reset failed</h1>
-        <p>The password reset link was invalid, possibly because it has already been used. Please request a new password reset.</p>
-    {% endif %}
-{% endblock %}
-
- -

密碼重置完成

- -

這是最後一個密碼重設模板,密碼重設成功後將顯示此模板以通知您。 創建/locallibrary/templates/registration/password_reset_complete.html,並為其提供以下內容:

- -
{% extends "base_generic.html" %}
-
-{% block content %}
-  <h1>The password has been changed!</h1>
-  <p><a href="{% url 'login' %}">log in again?</a></p>
-{% endblock %}
- -

Testing the new authentication pages

- -

現在您已經添加了URL配置並創建了所有這些模板,身份驗證頁面現在應該可以正常工作了!

- -

您可以通過嘗試使用以下URL登錄然後註銷超級用戶帳戶來測試新的身份驗證頁面:

- - - -

您可以通過登錄頁面中的鏈接測試密碼重置功能。 請注意,Django只會將重置電子郵件發送到已經存儲在其數據庫中的地址(用戶)!

- -
-

筆記:密碼重設系統要求您的網站支持電子郵件,這不在本文的討論範圍之內,因此該部分尚無法使用。 要進行測試,請將以下行放在settings.py文件的末尾。 這將記錄發送到控制台的所有電子郵件(因此您可以從控制台複製密碼重置鏈接)。

- -
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
-
- -

有關更多信息,請參閱發送電子郵件(Sending emailDjango文檔)。

-
- -

針對經過身份驗證的用戶進行測試

- -

本節介紹如何根據用戶是否登錄來有選擇地控制用戶看到的內容。

- -

在模板中測試

- -

您可以使用 \{{ user }}模板變量在模板中獲取有關當前登錄用戶的信息(默認情況下,就像我們在框架中一樣設置項目時,該信息會添加到模板上下文中)。

- -

通常,您將首先針對 \{{ user.is_authenticated }}模板變量進行測試,以確定該用戶是否有資格查看特定內容。 為了演示這一點,接下來,我們將更新邊欄,以在用戶註銷時顯示“登錄”鏈接,在用戶登錄時顯示“註銷”鏈接。

- -

打開基礎模板。 (/locallibrary/catalog/templates/base_generic.html) ,然後將以下文本複製到sidebar 塊中,緊接在endblock 模板標籤之前。

- -
  <ul class="sidebar-nav">
-
-    ...
-
-   {% if user.is_authenticated %}
-     <li>User: \{{ user.get_username }}</li>
-     <li><a href="{% url 'logout'%}?next=\{{request.path}}">Logout</a></li>
-   {% else %}
-     <li><a href="{% url 'login'%}?next=\{{request.path}}">Login</a></li>
-   {% endif %} 
-  </ul>
- -

如您所見,我們使用 if-else-endif 模板標籤根據 \{{ user.is_authenticated }} \ {{user.is_authenticated}}是否為真來有條件地顯示文本。 如果用戶通過了身份驗證,那麼我們知道我們有一個有效的用戶,因此我們調用 \{{ user.get_username }} 來顯示其名稱。

- -

我們使用url 模板標記和相應URL配置的名稱來創建登錄和註銷鏈接URL。 還要注意我們如何將?next=\{{request.path}}附加到URL的末尾。 這是在鏈接的URL的末尾添加一個URL參數,其中包含當前頁面的地址(URL)。 用戶成功登錄/註銷後,視圖將使用此``next''值將用戶重定向到他們首先單擊 login/logout 鏈接的頁面。

- -
-

注意:試試看! 如果您在主頁上,然後單擊側欄中的“Login/Logout”,那麼在操作完成後,您應該回到同一頁面。

-
- -

在視圖中測試

- -

如果您使用的是基於函數的視圖,則限制訪問函數的最簡單方法是將login_required 裝飾器應用於視圖函數,如下所示。 如果用戶已登錄,則您的視圖代碼將正常執行。 如果用戶未登錄,它將重定向到項目設置(settings.LOGIN_URL)中定義的登錄URL,並將當前的絕對路徑作為next URL參數傳遞。 如果用戶成功登錄,則他們將返回此頁面,但這次已通過身份驗證。

- -
from django.contrib.auth.decorators import login_required
-
-@login_required
-def my_view(request):
-    ...
- -
-

注意: 您可以通過在request.user.is_authenticated上進行測試來手動執行相同的操作,但是裝飾器要方便得多!

-
- -

同樣,在基於類的視圖中限制對登錄用戶的訪問權限的最簡單方法是從 LoginRequiredMixin. 派生。 您需要首先在父類列表中,在主視圖類之前聲明此混合。

- -
from django.contrib.auth.mixins import LoginRequiredMixin
-
-class MyView(LoginRequiredMixin, View):
-    ...
- -

它具有與 login_required 裝飾器完全相同的重定向行為。 如果用戶未通過身份驗證,也可以指定其他位置來重定向用戶 (login_url),並使用URL參數名稱代替“ next”來插入當前的絕對路徑(redirect_field_name).。

- -
class MyView(LoginRequiredMixin, View):
-    login_url = '/login/'
-    redirect_field_name = 'redirect_to'
-
- -

有關更多詳細信息,請在此處查看Django文檔

- -

範例—列出當前用戶的書籍

- -

現在,我們知道瞭如何將頁面限制為特定用戶,讓我們創建當前用戶借閱的書籍的視圖。

- -

不幸的是,我們還沒有任何方式讓用戶借書! 因此,在創建圖書清單之前,我們將首先擴展BookInstance 模型以支持借用的概念,並使用Django Admin應用程序將大量圖書借給我們的測試用戶。

- -

模型

- -

首先,我們將必須使用戶可以藉用BookInstance (我們已經具有statusdue_back ,但是在該模型和User之間還沒有任何關聯。我們將創建 一個使用ForeignKey (一對多)字段的方法,我們還需要一種簡單的機制來測試借出的書是否過期。
-
- 打開catalog/models.py,然後從 django.contrib.auth.models導入User 模型(將其添加到文件頂部的前一個導入行下面,因此User 可供使用它的後續代碼使用):

- -
from django.contrib.auth.models import User
-
- -

Ne接下來,將borrower 字段添加到BookInstance 模型中:

- -
borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
-
- -

當我們在這裡時,讓我們添加一個屬性,我們可以從模板中調用該屬性,以告知特定的圖書實例是否過期。 儘管我們可以在模板本身中進行計算,但是使用如下所示的屬性會更加高效。

- -

將此添加到文件頂部附近:

- -
from datetime import date
- -

現在,在BookInstance類中添加以下屬性定義:

- -
@property
-def is_overdue(self):
-    if self.due_back and date.today() > self.due_back:
-        return True
-    return False
- -
-

Note: 在進行比較之前,我們首先要驗證due_back是否為空。 空的 due_back字段將導致Django拋出錯誤而不是顯示頁面:空值不可比。 這不是我們希望用戶體驗的東西!

-
- -

現在,我們已經更新了模型,我們需要在項目上進行新的遷移,然後應用這些遷移:

- -
python3 manage.py makemigrations
-python3 manage.py migrate
-
- -

Admin

- -

現在打開catalog/admin.py,然後將list_displayfieldsets 中的borrower 字段添加到BookInstanceAdmin 類中,如下所示。 這將使該字段在“管理”部分中可見,以便我們可以在需要時將User 分配給BookInstance

- -
@admin.register(BookInstance)
-class BookInstanceAdmin(admin.ModelAdmin):
-    list_display = ('book', 'status', 'borrower', 'due_back', 'id')
-    list_filter = ('status', 'due_back')
-
-    fieldsets = (
-        (None, {
-            'fields': ('book','imprint', 'id')
-        }),
-        ('Availability', {
-            'fields': ('status', 'due_back','borrower')
-        }),
-    )
- -

Loan a few books

- -

現在可以將書借給特定用戶了,然後借出許多BookInstance 記錄。 將他們的borrowed 字段設置為測試用戶,status 為“借用”,並設置將來和將來的到期日。

- -
-

注意:我們不會詳細說明該過程,因為您已經知道如何使用管理網站!

-
- -

On loan view

- -

現在,我們將添加一個視圖,以獲取已借給當前用戶的所有書籍的列表。 我們將使用我們熟悉的相同的通用的基於類的列表視圖,但是這次我們還將導入並從LoginRequiredMixin派生,以便只有登錄的用戶才能調用此視圖。 我們還將選擇聲明template_name,而不使用默認值,因為我們最終可能會擁有一些不同的BookInstance記錄列表,並具有不同的視圖和模板。
-
- 將以下內容添加到catalog / views.py

- -
from django.contrib.auth.mixins import LoginRequiredMixin
-
-class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView):
-    """Generic class-based view listing books on loan to current user."""
-    model = BookInstance
-    template_name ='catalog/bookinstance_list_borrowed_user.html'
-    paginate_by = 10
-
-    def get_queryset(self):
-        return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')
- -

為了將查詢限制為僅針對當前用戶的BookInstance 對象,我們重新實現了 get_queryset(),如上所示。 請注意,“ o”是“借出”的存儲代碼,我們在due_back 日期之前訂購,以便最先顯示最早的項目。

- -

URL conf for on loan books

- -

現在打開/catalog/urls.py並添加指向上面視圖的path()(您可以將下面的文本複製到文件末尾)。

- -
urlpatterns += [
-    path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'),
-]
- -

Template for on loan books

- -

現在,我們需要為此頁面添加模板。 首先,創建模板文件 /catalog/templates/catalog/bookinstance_list_borrowed_user.html 並為其提供以下內容:

- -
{% extends "base_generic.html" %}
-
-{% block content %}
-    <h1>Borrowed books</h1>
-
-    {% if bookinstance_list %}
-    <ul>
-
-      {% for bookinst in bookinstance_list %}
-      <li class="{% if bookinst.is_overdue %}text-danger{% endif %}">
-        <a href="{% url 'book-detail' bookinst.book.pk %}">\{{bookinst.book.title}}</a> (\{{ bookinst.due_back }})
-      </li>
-      {% endfor %}
-    </ul>
-
-    {% else %}
-      <p>There are no books borrowed.</p>
-    {% endif %}
-{% endblock %}
- -

該模板與我們先前為BookAuthor 物件創建的模板非常相似。 這裡唯一的“新內容”是我們檢查在模型中添加的方法(bookinst.is_overdue),並使用它來更改過期項目的顏色。

- -

開發服務器運行時,現在應該可以在瀏覽器中的 http://127.0.0.1:8000/catalog/mybooks/ 上查看已登錄用戶的列表。 在您的用戶登錄和註銷後進行嘗試(在第二種情況下,應將您重定向到登錄頁面)。

- -

Add the list to the sidebar

- -

最後一步是將此新頁面的鏈接添加到側欄中。 我們將其放在同一部分中,在該部分中為登錄用戶顯示其他信息。

- -

打開基本模板 (/locallibrary/catalog/templates/base_generic.html) 並將粗體顯示的行添加到側邊欄中,如圖所示。

- -
 <ul class="sidebar-nav">
-   {% if user.is_authenticated %}
-   <li>User: \{{ user.get_username }}</li>
-   <li><a href="{% url 'my-borrowed' %}">My Borrowed</a></li>
-   <li><a href="{% url 'logout'%}?next=\{{request.path}}">Logout</a></li>
-   {% else %}
-   <li><a href="{% url 'login'%}?next=\{{request.path}}">Login</a></li>
-   {% endif %}
- </ul>
-
- -

What does it look like?

- -

當任何用戶登錄後,他們將在邊欄中看到“My Borrowed ”,並且書的列表顯示如下(第一本書沒有截止日期,這是我們希望在以後的教程中解決的錯誤!) 。

- -

Library - borrowed books by user

- -

Permissions

- -

權限與模型相關聯,並定義了具有權限的用戶可以在模型實例上執行的操作。 默認情況下,Django會自動為所有模型賦予添加,更改和刪除權限,從而允許具有權限的用戶通過管理站點執行關聯的操作。 您可以定義自己的模型權限,並將其授予特定用戶。 您還可以更改與同一模型的不同實例關聯的權限。

- -

這樣,對視圖和模板中的權限進行的測試就非常類似於對身份驗證狀態的測試(實際上,對權限的測試也對身份驗證進行了測試)。

- -

Models

- -

使用permissions 字段在模型“class Meta”部分中完成權限的定義。 您可以在元組中根據需要指定任意數量的權限,每個權限本身都在嵌套的元組中定義,其中包含權限名稱和權限顯示值。 例如,我們可以定義一個權限,以允許用戶標記已退回一本書,如下所示:

- -
class BookInstance(models.Model):
-    ...
-    class Meta:
-        ...
-        permissions = (("can_mark_returned", "Set book as returned"),)   
- -

然後,我們可以將權限分配給管理站點中的“圖書管理員”組。

- -

打開catalog/models.py,然後添加權限,如上所示。 您將需要重新運行遷移(調用 python3 manage.py makemigrationspython3 manage.py migrate)以適當地更新數據庫。

- -

模板

- -

當前用戶的權限存儲在名為 \{{ perms }}. 的模板變量中。 您可以使用關聯的Django "app"“應用”中的特定變量名稱來檢查當前用戶是否具有特定權限,例如 如果用戶具有此權限,則 \{{ perms.catalog.can_mark_returned }} 將為 True ,否則為False。 我們通常使用模板 {% if %} 標籤測試權限,如下所示:

- -
{% if perms.catalog.can_mark_returned %}
-    <!-- We can mark a BookInstance as returned. -->
-    <!-- Perhaps add code to link to a "book return" view here. -->
-{% endif %}
-
- -

視圖

- -

可以在功能視圖中使用permission_required 裝飾器來測試權限,或者在基於類的視圖中使用PermissionRequiredMixin. 來測試權限。 模式和行為與登錄身份驗證的模式和行為相同,儘管當然您可能必須合理地添加多個權限。

- -

視圖裝飾器函數:

- -
from django.contrib.auth.decorators import permission_required
-
-@permission_required('catalog.can_mark_returned')
-@permission_required('catalog.can_edit')
-def my_view(request):
-    ...
- -

基於類的視圖需要權限的混合。

- -
from django.contrib.auth.mixins import PermissionRequiredMixin
-
-class MyView(PermissionRequiredMixin, View):
-    permission_required = 'catalog.can_mark_returned'
-    # Or multiple permissions
-    permission_required = ('catalog.can_mark_returned', 'catalog.can_edit')
-    # Note that 'catalog.can_edit' is just an example
-    # the catalog application doesn't have such permission!
- -

範例

- -

我們不會在這裡更新LocalLibrary; 也許在下一個教程中!

- -

挑戰自己

- -

在本文的前面,我們向您展示瞭如何為當前用戶創建一個頁面,列出他們所借用的書。 現在的挑戰是創建一個僅對圖書館員可見的相似頁面,該頁面顯示所有已借書的書,其中包括每個借書人的名字。

- -

您應該能夠遵循與其他視圖相同的模式。 主要區別在於您只需要將視圖限制為圖書館員即可。 您可以根據用戶是否是工作人員來執行此操作(函數裝飾器:staff_member_required,模板變量: user.is_staff),但是我們建議您改用can_mark_returned 權限和PermissionRequiredMixin,如上一節所述。

- -
-

重要:請記住不要將您的超級用戶用於基於權限的測試(即使尚未定義權限,權限檢查也始終對超級用戶返回true!)。 而是創建一個圖書管理員用戶,並添加所需的功能。

-
- -

完成後,您的頁面應類似於以下屏幕截圖。All borrowed books, restricted to librarian

- - - -

總結

- -

出色的工作-您現在已經創建了一個網站,圖書館成員可以登錄並查看他們自己的內容,館員(具有正確的權限)可以用來查看所有借出的書及其借書人。 目前,我們仍在查看內容,但是當您要開始修改和添加數據時,將使用相同的原理和技術。

- -

在下一篇文章中,我們將研究如何使用Django表單來收集用戶輸入,然後開始修改一些存儲的數據。

- -

也可以看看

- - - -

{{PreviousMenuNext("Learn/Server-side/Django/Sessions", "Learn/Server-side/Django/Forms", "Learn/Server-side/Django")}}

- -

In this module

- - diff --git a/files/zh-tw/learn/server-side/django/authentication/index.md b/files/zh-tw/learn/server-side/django/authentication/index.md new file mode 100644 index 00000000000000..281fa740e47e96 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/authentication/index.md @@ -0,0 +1,704 @@ +--- +title: 'Django Tutorial Part 8: User authentication and permissions' +slug: Learn/Server-side/Django/Authentication +translation_of: Learn/Server-side/Django/Authentication +--- +{{LearnSidebar}}{{PreviousMenuNext("Learn/Server-side/Django/Sessions", "Learn/Server-side/Django/Forms", "Learn/Server-side/Django")}} + +在本教程中,我們將會展示如何允許用戶使用自己的帳戶登入到您的網站,以及如何根據用戶是否已登入和權限的不同來控制他們可以執行和查看的內容。作為展示的一部分,我們會擴展 [LocalLibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) 網站,添加登入頁面和登出頁面,以及用來查看已借閱的圖書的頁面 - 分為用戶與員工兩種不同頁面。 + + + + + + + + + + + + +
前提: + 完成至 + Django 線上教學 7: 會話(Sessions)框架為止的所有主題。 +
目標:了解如何設定與運用使用者驗證與權限機制。
+ +## 大綱 + +Django 提供認證和授權(“ permission”)系統,該系統建立在[上一教程](/zh-TW/docs/Learn/Server-side/Django/Sessions)中討論的會話框架的基礎上。透過它可以驗證用戶憑證並定義個別用戶能夠執行的操作。 該框架包括用於`Users` 和`Groups` 的內置模型(一般常用來一次性套用權限於一群用戶上的方式),用於指定用戶是否可以執行任務的權限/旗標,用於登入用戶的表單和視圖,以及 查看用於限制內容的工具。 + +> **備註:** 從 Django 角度而言,身份驗證系統需要做到非常通用,因此不提供其他網頁身份驗證系統中提供的某些功能。 需要解決一些常見問題的話可以透過第三方軟件包。 例如,限制登錄嘗試和透過第三方進行身份驗證(例如 OAuth)。 + +在本教程中,我們將會展示如何在[LocalLibrary](/zh-TW/docs/Learn/Server-side/Django/Tutorial_local_library_website)網站中啟用用戶身份驗證,並建立自己的登入和登出頁面,為模型添加權限以及控制對頁面的訪問。 我們將根據身份驗證/權限顯示為用戶或是圖書館員設計的已借出書籍列表。 + +身份驗證系統非常有彈性,您可以根據需要從頭開始構建 URL,表單,視圖和模板,只透過提供的 API 來登入用戶。 但是,在本文中,我們將為登入與登出頁面使用 Django 的“ stock”身份驗證視圖和表單。 我們仍然需要建立一些模板,但這很簡單。 + +我們還將向您展示如何建立權限,並在視圖和模板中檢查登入狀態和權限。 + +## Enabling authentication + +當我們[創建框架網站](/zh-TW/docs/Learn/Server-side/Django/skeleton_website)時(在教程 2 中),身份驗證已自動啟用,因此您此時無需執行任何其他操作。 + +> **備註:** 當我們使用`django-admin startproject`命令創建應用程序時,所有必要的配置都為我們完成了。 用戶和模型權限的數據庫表是在我們首次調用`python manage.py migrate`時創建的。 + +該配置是在項目文件(**locallibrary/locallibrary/settings.py**)的`INSTALLED_APPS` 和`MIDDLEWARE` 部分中設置的,如下所示: + +```python +INSTALLED_APPS = [ + ... + 'django.contrib.auth', #Core authentication framework and its default models. + 'django.contrib.contenttypes', #Django content type system (allows permissions to be associated with models). + .... + +MIDDLEWARE = [ + ... + 'django.contrib.sessions.middleware.SessionMiddleware', #Manages sessions across requests + ... + 'django.contrib.auth.middleware.AuthenticationMiddleware', #Associates users with requests using sessions. + .... +``` + +## Creating users and groups + +當我們在教程 4 中查看[Django 管理站](/zh-TW/docs/Learn/Server-side/Django/Admin_site)點時,您已經創建了第一個用戶(這是一個超級用戶,使用命令 p`python manage.py createsuperuser`創建)。 我們的超級用戶已經通過身份驗證,並且具有所有權限,因此我們需要創建一個測試用戶來代表普通站點用戶。 我們將使用管理站點來創建本地圖書館組和網站登錄名,因為這是最快的方法之一。 + +> **備註:** 您還可以通過編程方式創建用戶,如下所示。 例如,如果要開發一個界面以允許用戶創建自己的登錄名,則必須這樣做(您不應授予用戶訪問管理站點的權限)。 +> +> ```python +> from django.contrib.auth.models import User +> +> # Create user and save to the database +> user = User.objects.create_user('myusername', 'myemail@crazymail.com', 'mypassword') +> +> # Update fields and then save again +> user.first_name = 'John' +> user.last_name = 'Citizen' +> user.save() +> ``` + +在下面,我們將首先創建一個組,然後創建一個用戶。 即使我們還沒有添加庫成員的任何權限,但是如果以後需要添加,將它們一次添加到組中要比分別添加到每個成員要容易得多。 + +啟動開發服務器,然後在本地 Web 瀏覽器()中導航到管理站點。 使用您的超級用戶帳戶的憑據登錄到該站點。 管理站點的頂層顯示所有模型,按“ django 應用程序”排序。 在“**Authentication and Authorisation**”部分,您可以單擊**Users** 或**Groups**鏈接以查看其現有記錄。 + +![Admin site - add groups or users](admin_authentication_add.png) + +首先,讓我們為圖書館成員創建一個新組。 + +1. 單擊**Add**按鈕(在組旁邊)以創建一個新組; 輸入該組的名稱“Library Members”。 + ![Admin site - add group](admin_authentication_add_group.png) +2. 我們不需要該組的任何權限,因此只需按**SAVE** (您將被帶到組列表)。 + +現在讓我們創建一個用戶: + +1. 導航回到管理站點的主頁 +2. 單擊“用戶”旁邊的“添加”按鈕以打開“添加用戶”對話框。 + ![Admin site - add user pt1](admin_authentication_add_user_prt1.png) +3. 輸入適合您的測試用戶的用戶名和密碼/密碼確認 +4. 按**SAVE**創建用戶。 + 管理站點將創建新用戶,並立即將您帶到“更改用戶”視窗,您可以在其中更改用戶名並為用戶模型的可選字段添加信息。 這些字段包括名字,姓氏,電子郵件地址,用戶狀態和權限(僅應設置“活動”標誌)。 在更下方的位置,您可以指定用戶的組和權限,並查看與該用戶相關的重要日期(例如,他們的加入日期和上次登錄日期)。 + ![Admin site - add user pt2](admin_authentication_add_user_prt2.png) +5. 在“組”部分中,從“可用組”列表中選擇“**Library Member**”組,然後按框之間的右箭頭將其移至“選擇的組”框中。![Admin site - add user to group](admin_authentication_user_add_group.png) +6. 我們在這裡不需要執行任何其他操作,因此只需再次選擇**SAVE** 即可進入用戶列表。 + +就是這樣而已! 現在,您將擁有一個“普通庫成員”帳戶,您將可以使用該帳戶進行測試(一旦我們實現了頁面以使其能夠登錄)。 + +> **備註:** 您應該嘗試創建另一個庫成員用戶。 另外,為圖書館員創建一個組,並為其添加用戶! + +## Setting up your authentication views + +Django 提供了創建身份驗證頁面所需的幾乎所有內容,以處理“開箱即用”的登錄,註銷和密碼管理。 這包括 URL 映射器,視圖和表單,但不包括模板-我們必須創建自己的模板! + +在本節中,我們顯示如何將默認系統集成到 LocalLibrary 網站中並創建模板。 我們將它們放在主項目 URL 中。 + +> **備註:** 您不必使用任何代碼,但是您可能想要使用它,因為它使事情變得容易得多。 如果您更改用戶模型(一個高級主題!),幾乎可以肯定需要更改表單處理代碼,但是即使如此,您仍然可以使用庫存視圖功能。 + +> **備註:** 在這種情況下,我們可以合理地將身份驗證頁面(包括 URL 和模板)放入目錄應用程序中。 但是,如果我們有多個應用程序,最好將這種共享的登錄行為分開,並使其在整個站點中都可用,這就是我們在此處顯示的內容! + +### Project URLs + +將以下內容添加到項目 urls.py 文件(**locallibrary/locallibrary/urls.py**)文件的底部: + +```python +#Add Django site authentication urls (for login, logout, password management) +urlpatterns += [ + path('accounts/', include('django.contrib.auth.urls')), +] +``` + +導航到 URL(注意尾隨斜杠!),然後 Django 將顯示一個錯誤,指出找不到此 URL,並列出了它嘗試的所有 URL。 從中您可以看到將起作用的 URL,例如: + +> **備註:** 使用上述方法會在方括號中添加以下網址,這些網址可用於反轉網址映射。 您無需執行其他任何操作-上面的 url 映射會自動映射以下提到的 URL。 +> +> ```python +> accounts/ login/ [name='login'] +> accounts/ logout/ [name='logout'] +> accounts/ password_change/ [name='password_change'] +> accounts/ password_change/done/ [name='password_change_done'] +> accounts/ password_reset/ [name='password_reset'] +> accounts/ password_reset/done/ [name='password_reset_done'] +> accounts/ reset/// [name='password_reset_confirm'] +> accounts/ reset/done/ [name='password_reset_complete'] +> ``` + +現在嘗試導航到登錄 URL()。 這將再次失敗,但是會顯示一條錯誤消息,告訴您我們在模板搜索路徑上缺少必需的模板(**registration/login.html**)。 您會在頂部黃色部分看到以下幾行: + +```python +Exception Type: TemplateDoesNotExist +Exception Value: registration/login.html +``` + +下一步是在搜索路徑上創建註冊目錄,然後添加**login.html**文件。 + +### Template directory + +我們剛剛添加的 url(和隱式視圖)期望在模板搜索路徑中某個目錄**/registration/** 中找到它們的關聯模板。 + +對於這個網站,我們將 HTML 頁面放在**templates/registration/**目錄中。 此目錄應位於您的項目根目錄中,即與**catalog** 和**locallibrary** 文件夾相同的目錄中)。 請立即創建這些文件夾。 + +> **備註:** Your folder structure should now look like the below: +> locallibrary (django project folder) +> |\_catalog +> |\_locallibrary +> |\_templates **(new)** +> |\_registration + +為了使這些目錄對模板加載器可見(即將該目錄放置在模板搜索路徑中),請打開項目設置(**/locallibrary/locallibrary/settings.py**),並更新`TEMPLATES` 部分的`DIRS`行,如圖所示。 + +```python +TEMPLATES = [ + { + ... + 'DIRS': ['./templates',], + 'APP_DIRS': True, + ... +``` + +### Login template + +> **警告:** 本文提供的身份驗證模板是 Django 演示登錄模板的非常基本/稍作修改的版本。 您可能需要自定義它們以供自己使用! + +創建一個名為/**locallibrary/templates/registration/login.html**的新 HTML 文件。 為其提供以下內容: + +```html +{% extends "base_generic.html" %} + +{% block content %} + +{% if form.errors %} +

Your username and password didn't match. Please try again.

+{% endif %} + +{% if next %} + {% if user.is_authenticated %} +

Your account doesn't have access to this page. To proceed, + please login with an account that has access.

+ {% else %} +

Please login to see this page.

+ {% endif %} +{% endif %} + +
+{% csrf_token %} + +
+ \{{ form.username.label_tag }} + \{{ form.username }} +
+
+ \{{ form.password.label_tag }} + \{{ form.password }} +
+ +
+ + +
+
+ +{# Assumes you setup the password_reset view in your URLconf #} +

Lost password?

+ +{% endblock %} +``` + +該模板與我們之前看到的模板有一些相似之處-它擴展了我們的基本模板並覆蓋了內容塊。 其餘代碼是相當標準的表單處理代碼,我們將在以後的教程中進行討論。 現在您只需要知道的是,這將顯示一個表格,您可以在其中輸入用戶名和密碼,並且如果輸入無效的值,則在頁面刷新時會提示您輸入正確的值。 + +保存模板後,導航回到登錄頁面(),您應該看到類似以下內容: + +![Library login page v1](library_login.png) + +如果嘗試登錄將成功,並且您將被重定向到另一個頁面(默認情況下為)。 這裡的問題是,默認情況下,Django 期望登錄後將您帶到個人資料頁面,情況可能與否。 由於您尚未定義此頁面,因此會出現另一個錯誤! + +打開項目設置(**/locallibrary/locallibrary/settings.py**) ,然後將下面的文本添加到底部。 現在,當您登錄時,默認情況下應將您重定向到網站主頁。 + +```python +# Redirect to home URL after login (Default redirects to /accounts/profile/) +LOGIN_REDIRECT_URL = '/' +``` + +### Logout template + +如果您導航到登出 URL () ,則會看到一些奇怪的行為-您的用戶將被確定地註銷,但是您將被帶到**Admin** 註銷頁面。 那不是您想要的,僅僅是因為該頁面上的登錄鏈接將您帶到**Admin** 登錄屏幕(並且僅對具有`is_staff` 權限的用戶可用)。 + +創建並打開 /**locallibrary/templates/registration/logged_out.html**。 複製以下文本: + +```html +{% extends "base_generic.html" %} + +{% block content %} +

Logged out!

+ Click here to login again. +{% endblock %} +``` + +這個模板非常簡單。 它僅顯示一條消息,通知您已註銷,並提供一個鏈接,您可以按此鏈接返回登錄屏幕。 如果再次進入註銷 URL,您應該看到以下頁面: + +![Library logout page v1](library_logout.png) + +### Password reset templates + +默認的密碼重置系統使用電子郵件向用戶發送重置鏈接。 您需要創建表格以獲取用戶的電子郵件地址,發送電子郵件,允許他們輸入新密碼並在整個過程完成時註明。 + +以下模板可以用作起點。 + +#### 密碼重設表格 + +這是用於獲取用戶電子郵件地址(用於發送密碼重置電子郵件)的表格。 創建**/locallibrary/templates/registration/password_reset_form.html**,並為其提供以下內容: + +```html +{% extends "base_generic.html" %} + +{% block content %} +
+ {% csrf_token %} + {% if form.email.errors %} + {{ form.email.errors }} + {% endif %} +

\{{ form.email }}

+ +
+{% endblock %} +``` + +#### 密碼重置完成 + +收集您的電子郵件地址後,將顯示此表單。創建 **/locallibrary/templates/registration/password_reset_done.html**,並為其提供以下內容: + +```html +{% extends "base_generic.html" %} + +{% block content %} +

We've emailed you instructions for setting your password. If they haven't arrived in a few minutes, check your spam folder.

+{% endblock %} +``` + +#### 密碼重置電子郵件 + +該模板提供了 HTML 電子郵件的文本,其中包含我們將發送給用戶的重置鏈接。 創建**/locallibrary/templates/registration/password_reset_email.html**,並為其提供以下內容: + +```html +Someone asked for password reset for email \{{ email }}. Follow the link below: +\{{ protocol}}://\{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} +``` + +#### 密碼重置確認 + +單擊密碼重置電子郵件中的鏈接後,即可在此頁面輸入新密碼。 創建 **/locallibrary/templates/registration/password_reset_confirm.html**,並為其提供以下內容: + +```html +{% extends "base_generic.html" %} + +{% block content %} + {% if validlink %} +

Please enter (and confirm) your new password.

+
+
+ +
+ + + + + + + + + + + + + +
\{{ form.new_password1.errors }} + \{{ form.new_password1 }}
\{{ form.new_password2.errors }} + \{{ form.new_password2 }}
+
+ {% else %} +

Password reset failed

+

The password reset link was invalid, possibly because it has already been used. Please request a new password reset.

+ {% endif %} +{% endblock %} +``` + +#### 密碼重置完成 + +這是最後一個密碼重設模板,密碼重設成功後將顯示此模板以通知您。 創建**/locallibrary/templates/registration/password_reset_complete.html**,並為其提供以下內容: + +```html +{% extends "base_generic.html" %} + +{% block content %} +

The password has been changed!

+

log in again?

+{% endblock %} +``` + +### Testing the new authentication pages + +現在您已經添加了 URL 配置並創建了所有這些模板,身份驗證頁面現在應該可以正常工作了! + +您可以通過嘗試使用以下 URL 登錄然後註銷超級用戶帳戶來測試新的身份驗證頁面: + +- +- + +您可以通過登錄頁面中的鏈接測試密碼重置功能。 **請注意,Django 只會將重置電子郵件發送到已經存儲在其數據庫中的地址(用戶)!** + +> **備註:** 密碼重設系統要求您的網站支持電子郵件,這不在本文的討論範圍之內,因此該部分尚無法使用。 要進行測試,請將以下行放在 settings.py 文件的末尾。 這將記錄發送到控制台的所有電子郵件(因此您可以從控制台複製密碼重置鏈接)。 +> +> ```python +> EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' +> ``` +> +> 有關更多信息,請參閱發送電子郵件([Sending email](https://docs.djangoproject.com/en/2.0/topics/email/)Django 文檔)。 + +## 針對經過身份驗證的用戶進行測試 + +本節介紹如何根據用戶是否登錄來有選擇地控制用戶看到的內容。 + +### 在模板中測試 + +您可以使用 `\{{ user }}`模板變量在模板中獲取有關當前登錄用戶的信息(默認情況下,就像我們在框架中一樣設置項目時,該信息會添加到模板上下文中)。 + +通常,您將首先針對 `\{{ user.is_authenticated }}`模板變量進行測試,以確定該用戶是否有資格查看特定內容。 為了演示這一點,接下來,我們將更新邊欄,以在用戶註銷時顯示“登錄”鏈接,在用戶登錄時顯示“註銷”鏈接。 + +打開基礎模板。 (**/locallibrary/catalog/templates/base_generic.html**) ,然後將以下文本複製到`sidebar` 塊中,緊接在`endblock` 模板標籤之前。 + +```html + +``` + +如您所見,我們使用 `if`-`else`-`endif` 模板標籤根據 `\{{ user.is_authenticated }}` \ {{user.is_authenticated}}是否為真來有條件地顯示文本。 如果用戶通過了身份驗證,那麼我們知道我們有一個有效的用戶,因此我們調用 **\\{{ user.get_username }}** 來顯示其名稱。 + +我們使用`url` 模板標記和相應 URL 配置的名稱來創建登錄和註銷鏈接 URL。 還要注意我們如何將`?next=\{{request.path}}`附加到 URL 的末尾。 這是在鏈接的 URL 的末尾添加一個 URL 參數,其中包含當前頁面的地址(URL)。 用戶成功登錄/註銷後,視圖將使用此\`\``next`''值將用戶重定向到他們首先單擊 login/logout 鏈接的頁面。 + +> **備註:** 試試看! 如果您在主頁上,然後單擊側欄中的“Login/Logout”,那麼在操作完成後,您應該回到同一頁面。 + +### 在視圖中測試 + +如果您使用的是基於函數的視圖,則限制訪問函數的最簡單方法是將`login_required` 裝飾器應用於視圖函數,如下所示。 如果用戶已登錄,則您的視圖代碼將正常執行。 如果用戶未登錄,它將重定向到項目設置(`settings.LOGIN_URL`)中定義的登錄 URL,並將當前的絕對路徑作為`next` URL 參數傳遞。 如果用戶成功登錄,則他們將返回此頁面,但這次已通過身份驗證。 + +```python +from django.contrib.auth.decorators import login_required + +@login_required +def my_view(request): + ... +``` + +> **備註:** 您可以通過在`request.user.is_authenticated`上進行測試來手動執行相同的操作,但是裝飾器要方便得多! + +同樣,在基於類的視圖中限制對登錄用戶的訪問權限的最簡單方法是從 `LoginRequiredMixin`. 派生。 您需要首先在父類列表中,在主視圖類之前聲明此混合。 + +```python +from django.contrib.auth.mixins import LoginRequiredMixin + +class MyView(LoginRequiredMixin, View): + ... +``` + +它具有與 `login_required` 裝飾器完全相同的重定向行為。 如果用戶未通過身份驗證,也可以指定其他位置來重定向用戶 (`login_url`),並使用 URL 參數名稱代替“ next”來插入當前的絕對路徑(`redirect_field_name`).。 + +```python +class MyView(LoginRequiredMixin, View): + login_url = '/login/' + redirect_field_name = 'redirect_to' +``` + +有關更多詳細信息,請在此處查看[Django 文檔](https://docs.djangoproject.com/en/2.0/topics/auth/default/#limiting-access-to-logged-in-users)。 + +## 範例—列出當前用戶的書籍 + +現在,我們知道瞭如何將頁面限制為特定用戶,讓我們創建當前用戶借閱的書籍的視圖。 + +不幸的是,我們還沒有任何方式讓用戶借書! 因此,在創建圖書清單之前,我們將首先擴展`BookInstance` 模型以支持借用的概念,並使用 Django Admin 應用程序將大量圖書借給我們的測試用戶。 + +### 模型 + +首先,我們將必須使用戶可以藉用`BookInstance` (我們已經具有`status` 和`due_back` ,但是在該模型和 User 之間還沒有任何關聯。我們將創建 一個使用`ForeignKey` (一對多)字段的方法,我們還需要一種簡單的機制來測試借出的書是否過期。 + +打開**catalog/models.py**,然後從 `django.contrib.auth.models`導入`User` 模型(將其添加到文件頂部的前一個導入行下面,因此`User` 可供使用它的後續代碼使用): + +```python +from django.contrib.auth.models import User +``` + +Ne 接下來,將`borrower` 字段添加到`BookInstance` 模型中: + + borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) + +當我們在這裡時,讓我們添加一個屬性,我們可以從模板中調用該屬性,以告知特定的圖書實例是否過期。 儘管我們可以在模板本身中進行計算,但是使用如下所示的[屬性](https://docs.python.org/3/library/functions.html#property)會更加高效。 + +將此添加到文件頂部附近: + +```python +from datetime import date +``` + +現在,在`BookInstance`類中添加以下屬性定義: + +```python +@property +def is_overdue(self): + if self.due_back and date.today() > self.due_back: + return True + return False +``` + +> **備註:** 在進行比較之前,我們首先要驗證`due_back`是否為空。 空的 `due_back`字段將導致 Django 拋出錯誤而不是顯示頁面:空值不可比。 這不是我們希望用戶體驗的東西! + +現在,我們已經更新了模型,我們需要在項目上進行新的遷移,然後應用這些遷移: + +```bash +python3 manage.py makemigrations +python3 manage.py migrate +``` + +### Admin + +現在打開**catalog/admin.py**,然後將`list_display` 和`fieldsets` 中的`borrower` 字段添加到`BookInstanceAdmin` 類中,如下所示。 這將使該字段在“管理”部分中可見,以便我們可以在需要時將`User` 分配給`BookInstance` 。 + +```python +@admin.register(BookInstance) +class BookInstanceAdmin(admin.ModelAdmin): + list_display = ('book', 'status', 'borrower', 'due_back', 'id') + list_filter = ('status', 'due_back') + + fieldsets = ( + (None, { + 'fields': ('book','imprint', 'id') + }), + ('Availability', { + 'fields': ('status', 'due_back','borrower') + }), + ) +``` + +### Loan a few books + +現在可以將書借給特定用戶了,然後借出許多`BookInstance` 記錄。 將他們的`borrowed` 字段設置為測試用戶,`status` 為“借用”,並設置將來和將來的到期日。 + +> **備註:** 我們不會詳細說明該過程,因為您已經知道如何使用管理網站! + +### On loan view + +現在,我們將添加一個視圖,以獲取已借給當前用戶的所有書籍的列表。 我們將使用我們熟悉的相同的通用的基於類的列表視圖,但是這次我們還將導入並從`LoginRequiredMixin`派生,以便只有登錄的用戶才能調用此視圖。 我們還將選擇聲明`template_name`,而不使用默認值,因為我們最終可能會擁有一些不同的 BookInstance 記錄列表,並具有不同的視圖和模板。 + +將以下內容添加到**catalog / views.py**: + +```python +from django.contrib.auth.mixins import LoginRequiredMixin + +class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView): + """Generic class-based view listing books on loan to current user.""" + model = BookInstance + template_name ='catalog/bookinstance_list_borrowed_user.html' + paginate_by = 10 + + def get_queryset(self): + return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back') +``` + +為了將查詢限制為僅針對當前用戶的`BookInstance` 對象,我們重新實現了 `get_queryset()`,如上所示。 請注意,“ o”是“借出”的存儲代碼,我們在`due_back` 日期之前訂購,以便最先顯示最早的項目。 + +### URL conf for on loan books + +現在打開**/catalog/urls.py**並添加指向上面視圖的`path()`(您可以將下面的文本複製到文件末尾)。 + +```python +urlpatterns += [ + path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'), +] +``` + +### Template for on loan books + +現在,我們需要為此頁面添加模板。 首先,創建模板文件 **/catalog/templates/catalog/bookinstance_list_borrowed_user.html** 並為其提供以下內容: + +```python +{% extends "base_generic.html" %} + +{% block content %} +

Borrowed books

+ + {% if bookinstance_list %} +
    + + {% for bookinst in bookinstance_list %} +
  • + \{{bookinst.book.title}} (\{{ bookinst.due_back }}) +
  • + {% endfor %} +
+ + {% else %} +

There are no books borrowed.

+ {% endif %} +{% endblock %} +``` + +該模板與我們先前為`Book` 和`Author` 物件創建的模板非常相似。 這裡唯一的“新內容”是我們檢查在模型中添加的方法(`bookinst.is_overdue`),並使用它來更改過期項目的顏色。 + +開發服務器運行時,現在應該可以在瀏覽器中的 上查看已登錄用戶的列表。 在您的用戶登錄和註銷後進行嘗試(在第二種情況下,應將您重定向到登錄頁面)。 + +### Add the list to the sidebar + +最後一步是將此新頁面的鏈接添加到側欄中。 我們將其放在同一部分中,在該部分中為登錄用戶顯示其他信息。 + +打開基本模板 (**/locallibrary/catalog/templates/base_generic.html**) 並將粗體顯示的行添加到側邊欄中,如圖所示。 + +```python + +``` + +### What does it look like? + +當任何用戶登錄後,他們將在邊欄中看到“_My Borrowed_ ”,並且書的列表顯示如下(第一本書沒有截止日期,這是我們希望在以後的教程中解決的錯誤!) 。 + +![Library - borrowed books by user](library_borrowed_by_user.png) + +## Permissions + +權限與模型相關聯,並定義了具有權限的用戶可以在模型實例上執行的操作。 默認情況下,Django 會自動為所有模型賦予添加,更改和刪除權限,從而允許具有權限的用戶通過管理站點執行關聯的操作。 您可以定義自己的模型權限,並將其授予特定用戶。 您還可以更改與同一模型的不同實例關聯的權限。 + +這樣,對視圖和模板中的權限進行的測試就非常類似於對身份驗證狀態的測試(實際上,對權限的測試也對身份驗證進行了測試)。 + +### Models + +使用`permissions` 字段在模型“`class Meta`”部分中完成權限的定義。 您可以在元組中根據需要指定任意數量的權限,每個權限本身都在嵌套的元組中定義,其中包含權限名稱和權限顯示值。 例如,我們可以定義一個權限,以允許用戶標記已退回一本書,如下所示: + +```python +class BookInstance(models.Model): + ... + class Meta: + ... + permissions = (("can_mark_returned", "Set book as returned"),) +``` + +然後,我們可以將權限分配給管理站點中的“圖書管理員”組。 + +打開**catalog/models.py,**然後添加權限,如上所示。 您將需要重新運行遷移(調用 `python3 manage.py makemigrations` 和`python3 manage.py migrate`)以適當地更新數據庫。 + +### 模板 + +當前用戶的權限存儲在名為 `\{{ perms }}`. 的模板變量中。 您可以使用關聯的 Django "app"“應用”中的特定變量名稱來檢查當前用戶是否具有特定權限,例如 如果用戶具有此權限,則 `\{{ perms.catalog.can_mark_returned }}` 將為 `True` ,否則為`False`。 我們通常使用模板 `{% if %}` 標籤測試權限,如下所示: + +```python +{% if perms.catalog.can_mark_returned %} + + +{% endif %} +``` + +### 視圖 + +可以在功能視圖中使用`permission_required` 裝飾器來測試權限,或者在基於類的視圖中使用`PermissionRequiredMixin`. 來測試權限。 模式和行為與登錄身份驗證的模式和行為相同,儘管當然您可能必須合理地添加多個權限。 + +視圖裝飾器函數: + +```python +from django.contrib.auth.decorators import permission_required + +@permission_required('catalog.can_mark_returned') +@permission_required('catalog.can_edit') +def my_view(request): + ... +``` + +基於類的視圖需要權限的混合。 + +```python +from django.contrib.auth.mixins import PermissionRequiredMixin + +class MyView(PermissionRequiredMixin, View): + permission_required = 'catalog.can_mark_returned' + # Or multiple permissions + permission_required = ('catalog.can_mark_returned', 'catalog.can_edit') + # Note that 'catalog.can_edit' is just an example + # the catalog application doesn't have such permission! +``` + +### 範例 + +我們不會在這裡更新 LocalLibrary; 也許在下一個教程中! + +## 挑戰自己 + +在本文的前面,我們向您展示瞭如何為當前用戶創建一個頁面,列出他們所借用的書。 現在的挑戰是創建一個僅對圖書館員可見的相似頁面,該頁面顯示所有已借書的書,其中包括每個借書人的名字。 + +您應該能夠遵循與其他視圖相同的模式。 主要區別在於您只需要將視圖限制為圖書館員即可。 您可以根據用戶是否是工作人員來執行此操作(函數裝飾器:`staff_member_required`,模板變量: `user.is_staff`),但是我們建議您改用`can_mark_returned` 權限和`PermissionRequiredMixin`,如上一節所述。 + +> **警告:** 請記住不要將您的超級用戶用於基於權限的測試(即使尚未定義權限,權限檢查也始終對超級用戶返回 true!)。 而是創建一個圖書管理員用戶,並添加所需的功能。 + +完成後,您的頁面應類似於以下屏幕截圖。![All borrowed books, restricted to librarian](library_borrowed_all.png) + +## 總結 + +出色的工作-您現在已經創建了一個網站,圖書館成員可以登錄並查看他們自己的內容,館員(具有正確的權限)可以用來查看所有借出的書及其借書人。 目前,我們仍在查看內容,但是當您要開始修改和添加數據時,將使用相同的原理和技術。 + +在下一篇文章中,我們將研究如何使用 Django 表單來收集用戶輸入,然後開始修改一些存儲的數據。 + +## 也可以看看 + +- [User authentication in Django](https://docs.djangoproject.com/en/2.0/topics/auth/) (Django docs) +- [Using the (default) Django authentication system](https://docs.djangoproject.com/en/2.0/topics/auth/default//) (Django docs) +- [Introduction to class-based views > Decorating class-based views](https://docs.djangoproject.com/en/2.0/topics/class-based-views/intro/#decorating-class-based-views) (Django docs) + +{{PreviousMenuNext("Learn/Server-side/Django/Sessions", "Learn/Server-side/Django/Forms", "Learn/Server-side/Django")}} + +## In this module + +- [Django introduction](/en-US/docs/Learn/Server-side/Django/Introduction) +- [Setting up a Django development environment](/en-US/docs/Learn/Server-side/Django/development_environment) +- [Django Tutorial: The Local Library website](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django Tutorial Part 2: Creating a skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) +- [Django Tutorial Part 3: Using models](/en-US/docs/Learn/Server-side/Django/Models) +- [Django Tutorial Part 4: Django admin site](/en-US/docs/Learn/Server-side/Django/Admin_site) +- [Django Tutorial Part 5: Creating our home page](/en-US/docs/Learn/Server-side/Django/Home_page) +- [Django Tutorial Part 6: Generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views) +- [Django Tutorial Part 7: Sessions framework](/en-US/docs/Learn/Server-side/Django/Sessions) +- [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/Authentication) +- [Django Tutorial Part 9: Working with forms](/en-US/docs/Learn/Server-side/Django/Forms) +- [Django Tutorial Part 10: Testing a Django web application](/en-US/docs/Learn/Server-side/Django/Testing) +- [Django Tutorial Part 11: Deploying Django to production](/en-US/docs/Learn/Server-side/Django/Deployment) +- [Django web application security](/en-US/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django mini blog](/en-US/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/deployment/index.html b/files/zh-tw/learn/server-side/django/deployment/index.html deleted file mode 100644 index 71859db0c40ded..00000000000000 --- a/files/zh-tw/learn/server-side/django/deployment/index.html +++ /dev/null @@ -1,675 +0,0 @@ ---- -title: 'Django Tutorial Part 11: Deploying Django to production' -slug: Learn/Server-side/Django/Deployment -translation_of: Learn/Server-side/Django/Deployment ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Django/Testing", "Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}}
- -

現在,您已經創建(並測試)了一個令人敬畏的 LocalLibrary 網站,如果您希望將其安裝在公共 Web 服務器上,以便圖書館工作人員、和成員,可以通過 Internet 訪問它。本文概述如何找到主機來部署您的網站,以及您需要做什麼,才能讓您的網站準備好生產環境。

- - - - - - - - - - - - -
Prerequisites:Complete all previous tutorial topics, including Django Tutorial Part 10: Testing a Django web application.
Objective:To learn where and how you can deploy a Django app to production.
- -

Overview

- -

Once your site is finished (or finished "enough" to start public testing) you're going to need to host it somewhere more public and accessible than your personal development computer.

- -

Up to now you've been working in a development environment, using the Django development web server to share your site to the local browser/network, and running your website with (insecure) development settings that expose debug and other private information. Before you can host a website externally you're first going to have to:

- -
    -
  • Make a few changes to your project settings.
  • -
  • Choose an environment for hosting the Django app.
  • -
  • Choose an environment for hosting any static files.
  • -
  • Set up a production-level infrastructure for serving your website.
  • -
- -

This tutorial provides some guidance on your options for choosing a hosting site, a brief overview of what you need to do in order to get your Django app ready for production, and a worked example of how to install the LocalLibrary website onto the Heroku cloud hosting service.

- -

What is a production environment?

- -

The production environment is the environment provided by the server computer where you will run your website for external consumption. The environment includes:

- -
    -
  • Computer hardware on which the website runs.
  • -
  • Operating system (e.g. Linux, Windows).
  • -
  • Programming language runtime and framework libraries on top of which your website is written.
  • -
  • Web server used to serve pages and other content (e.g. Nginx, Apache).
  • -
  • Application server that passes "dynamic" requests between your Django website and the webserver.
  • -
  • Databases on which your website is dependent.
  • -
- -
-

Note: Depending on how your production is configured you might also have a reverse proxy, load balancer, etc.

-
- -

The server computer could be located on your premises and connected to the Internet by a fast link, but it is far more common to use a computer that is hosted "in the cloud". What this actually means is that your code is run on some remote computer (or possibly a "virtual" computer) in your hosting company's data center(s). The remote server will usually offer some guaranteed level of computing resources (e.g. CPU, RAM, storage memory, etc.) and Internet connectivity for a certain price.

- -

This sort of remotely accessible computing/networking hardware is referred to as Infrastructure as a Service (IaaS). Many IaaS vendors provide options to preinstall a particular operating system, onto which you must install the other components of your production environment. Other vendors allow you to select more fully-featured environments, perhaps including a complete Django and web-server setup.

- -
-

Note: Pre-built environments can make setting up your website very easy because they reduce the configuration, but the available options may limit you to an unfamiliar server (or other components) and may be based on an older version of the OS. Often it is better to install components yourself, so that you get the ones that you want, and when you need to upgrade parts of the system, you have some idea where to start!

-
- -

Other hosting providers support Django as part of a Platform as a Service (PaaS) offering. In this sort of hosting you don't need to worry about most of your production environment (web server, application server, load balancers) as the host platform takes care of those for you (along with most of what you need to do in order to scale your application). That makes deployment quite easy, because you just need to concentrate on your web application and not all the other server infrastructure.

- -

Some developers will choose the increased flexibility provided by IaaS over PaaS, while others will appreciate the reduced maintenance overhead and easier scaling of PaaS. When you're getting started, setting up your website on a PaaS system is much easier, and so that is what we'll do in this tutorial.

- -
-

Tip: If you choose a Python/Django-friendly hosting provider they should provide instructions on how to set up a Django website using different configurations of webserver, application server, reverse proxy, etc (this won't be relevant if you choose a PaaS). For example, there are many step-by-step guides for various configurations in the Digital Ocean Django community docs.

-
- -

Choosing a hosting provider

- -

There are well over 100 hosting providers that are known to either actively support or work well with Django (you can find a fairly extensive list at Djangofriendly hosts). These vendors provide different types of environments (IaaS, PaaS), and different levels of computing and network resources at different prices.

- -

Some of the things to consider when choosing a host:

- -
    -
  • How busy your site is likely to be and the cost of data and computing resources required to meet that demand.
  • -
  • Level of support for scaling horizontally (adding more machines) and vertically (upgrading to more powerful machines) and the costs of doing so.
  • -
  • Where the supplier has data centres, and hence where access is likely to be fastest.
  • -
  • The host's historical uptime and downtime performance.
  • -
  • Tools provided for managing the site — are they easy to use and are they secure (e.g. SFTP vs FTP).
  • -
  • Inbuilt frameworks for monitoring your server.
  • -
  • Known limitations. Some hosts will deliberately block certain services (e.g. email) . Others offer only a certain number of hours of "live time" in some price tiers, or only offer a small amount of storage.
  • -
  • Additional benefits. Some providers will offer free domain names and support for SSL certificates that you would otherwise have to pay for.
  • -
  • Whether the "free" tier you're relying on expires over time, and whether the cost of migrating to a more expensive tier means you would have been better off using some other service in the first place!
  • -
- -

The good news when you're starting out is that there are quite a few sites that provide "evaluation", "developer", or "hobbyist" computing environments for "free". These are always fairly resource constrained/limited environments, and you do need to be aware that they may expire after some introductory period. They are however great for testing low traffic sites in a real environment, and can provide an easy migration to paying for more resources when your site gets busier. Popular choices in this category include Heroku, Python Anywhere, Amazon Web Services, Microsoft Azure, etc.

- -

Many providers also have a "basic" tier that provides more useful levels of computing power and fewer limitations. Digital Ocean and Python Anywhere are examples of popular hosting providers that offer a relatively inexpensive basic computing tier (in the $5 to $10USD per month range).

- -
-

Note: Remember that price is not the only selection criteria. If your website is successful, it may turn out that scalability is the most important consideration.

-
- -

Getting your website ready to publish

- -

The Django skeleton website created using the django-admin and manage.py tools are configured to make development easier. Many of the Django project settings (specified in settings.py) should be different for production, either for security or performance reasons.

- -
-

Tip: It is common to have a separate settings.py file for production, and to import sensitive settings from a separate file or an environment variable. This file should then be protected, even if the rest of the source code is available on a public repository.

-
- -

The critical settings that you must check are:

- -
    -
  • DEBUG. This should be set as False in production (DEBUG = False). This stops the sensitive/confidential debug trace and variable information from being displayed.
  • -
  • SECRET_KEY. This is a large random value used for CSRF protection etc. It is important that the key used in production is not in source control or accessible outside the production server. The Django documents suggest that this might best be loaded from an environment variable or read from a serve-only file. -
    # Read SECRET_KEY from an environment variable
    -import os
    -SECRET_KEY = os.environ['SECRET_KEY']
    -
    -#OR
    -
    -#Read secret key from a file
    -with open('/etc/secret_key.txt') as f:
    -    SECRET_KEY = f.read().strip()
    -
  • -
- -

Let's change the LocalLibrary application so that we read our SECRET_KEY and DEBUG variables from environment variables if they are defined, but otherwise use the default values in the configuration file.

- -

Open /locallibrary/settings.py, disable the original SECRET_KEY configuration and add the new lines as shown below in bold. During development no environment variable will be specified for the key, so the default value will be used (it shouldn't matter what key you use here, or if the key "leaks", because you won't use it in production).

- -
# SECURITY WARNING: keep the secret key used in production secret!
-# SECRET_KEY = 'cg#p$g+j9tax!#a3cup@1$8obt2_+&k3q+pmu)5%asj6yjpkag'
-import os
-SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'cg#p$g+j9tax!#a3cup@1$8obt2_+&k3q+pmu)5%asj6yjpkag')
-
- -

Then comment out the existing DEBUG setting and add the new line shown below.

- -
# SECURITY WARNING: don't run with debug turned on in production!
-# DEBUG = True
-DEBUG = bool( os.environ.get('DJANGO_DEBUG', True) )
-
- -

The value of the DEBUG will be True by default, but will be False if the value of the DJANGO_DEBUG environment variable is set to an empty string, e.g. DJANGO_DEBUG=''.

- -
-

Note: It would be more intuitive if we could just set and unset the DJANGO_DEBUG environment variable to True and False directly, rather than using "any string" or "empty string" (respectively). Unfortunately environment variable values are stored as Python strings, and the only string that evaluates as False is the empty string (e.g. bool('')==False).

-
- -

A full checklist of settings you might want to change is provided in Deployment checklist (Django docs). You can also list a number of these using the terminal command below:

- -
python3 manage.py check --deploy
-
- -

Example: Installing LocalLibrary on Heroku

- -

This section provides a practical demonstration of how to install LocalLibrary on the Heroku PaaS cloud.

- -

Why Heroku?

- -

Heroku is one of the longest running and popular cloud-based PaaS services. It originally supported only Ruby apps, but now can be used to host apps from many programming environments, including Django!

- -

We are choosing to use Heroku for several reasons:

- -
    -
  • Heroku has a free tier that is really free (albeit with some limitations).
  • -
  • As a PaaS, Heroku takes care of a lot of the web infrastructure for us. This makes it much easier to get started, because you don't worry about servers, load balancers, reverse proxies, or any of the other web infrastructure that Heroku provides for us under the hood.
  • -
  • While it does have some limitations these will not affect this particular application. For example: -
      -
    • Heroku provides only short-lived storage so user-uploaded files cannot safely be stored on Heroku itself.
    • -
    • The free tier will sleep an inactive web app if there are no requests within a half hour period. The site may then take several seconds to respond when it is woken up.
    • -
    • The free tier limits the time that your site is running to a certain amount of hours every month (not including the time that the site is "asleep"). This is fine for a low use/demonstration site, but will not be suitable if 100% uptime is required.
    • -
    • Other limitations are listed in Limits (Heroku docs).
    • -
    -
  • -
  • Mostly it just works, and if you end up loving it, scaling your app is very easy.
  • -
- -

While Heroku is perfect for hosting this demonstration it may not be perfect for your real website. Heroku makes things easy to set up and scale, at the cost of being less flexible, and potentially a lot more expensive once you get out of the free tier.

- -

How does Heroku work?

- -

Heroku runs Django websites within one or more "Dynos", which are isolated, virtualized Unix containers that provide the environment required to run an application. The dynos are completely isolated and have an ephemeral file system (a short-lived file system that is cleaned/emptied every time the dyno restarts). The only thing that dynos share by default are application configuration variables. Heroku internally uses a load balancer to distribute web traffic to all "web" dynos. Since nothing is shared between them, Heroku can scale an app horizontally simply by adding more dynos (though of course you may also need to scale your database to accept additional connections).

- -

Because the file system is ephemeral you can't install services required by your application directly (e.g. databases, queues, caching systems, storage, email services, etc). Instead Heroku web applications use backing services provided as independent "add-ons" by Heroku or 3rd parties. Once attached to your web application, the dynos access the services using information contained in application configuration variables.

- -

In order to execute your application Heroku needs to be able to set up the appropriate environment and dependencies, and also understand how it is launched. For Django apps we provide this information in a number of text files:

- -
    -
  • runtime.txt: the programming language and version to use.
  • -
  • requirements.txt: the Python component dependencies, including Django.
  • -
  • Procfile: A list of processes to be executed to start the web application. For Django this will usually be the Gunicorn web application server (with a .wsgi script).
  • -
  • wsgi.py: WSGI configuration to call our Django application in the Heroku environment.
  • -
- -

Developers interact with Heroku using a special client app/terminal, which is much like a Unix bash script. This allows you to upload code that is stored in a git repository, inspect the running processes, see logs, set configuration variables and much more!

- -

In order to get our application to work on Heroku we'll need to put our Django web application into a git repository, add the files above, integrate with a database add-on, and make changes to properly handle static files.

- -

Once we've done all that we can set up a Heroku account, get the Heroku client, and use it to install our website.

- -
-

Note: The instructions below reflect how to work with Heroku at time of writing. If Heroku significantly change their processes, you may wish to instead check their setup documents: Getting Started on Heroku with Django.

-
- -

That's all the overview you need in order to get started (see How Heroku works for a more comprehensive guide).

- -

Creating an application repository in Github

- -

Heroku is closely integrated with the git source code version control system, using it to upload/synchronise any changes you make to the live system. It does this by adding a new heroku "remote" repository named heroku pointing to a repository for your source on the Heroku cloud. During development you use git to store changes on your "master" repository. When you want to deploy your site, you sync your changes to the Heroku repository.

- -
-

Note: If you're used to following good software development practices you are probably already using git or some other SCM system. If you already have a git repository, then you can skip this step.

-
- -

There are a lot of ways of to work with git, but one of the easiest is to first set up an account on Github, create the repository there, and then sync to it locally:

- -
    -
  1. Visit https://github.com/ and create an account.
  2. -
  3. Once you are logged in, click the + link in the top toolbar and select New repository.
  4. -
  5. Fill in all the fields on this form. While these are not compulsory, they are strongly recommended. -
      -
    • Enter a new repository name (e.g. django_local_library), and description (e.g. "Local Library website written in Django".
    • -
    • Choose Python in the Add .gitignore selection list.
    • -
    • Choose your preferred license in the Add license selection list.
    • -
    • Check Initialize this repository with a README.
    • -
    -
  6. -
  7. Press Create repository.
  8. -
  9. Click the green "Clone or download" button on your new repo page.
  10. -
  11. Copy the URL value from the text field inside the dialog box that appears (it should be something like: https://github.com/<your_git_user_id>/django_local_library.git).
  12. -
- -

Now the repository ("repo") is created we are going to want to clone it on our local computer:

- -
    -
  1. Install git for your local computer (you can find versions for different platforms here).
  2. -
  3. Open a command prompt/terminal and clone your repository using the URL you copied above: -
    git clone https://github.com/<your_git_user_id>/django_local_library.git
    -
    - This will create the repository below the current point.
  4. -
  5. Navigate into the new repo. -
    cd django_local_library.git
    -
  6. -
- -

The final step is to copy in your application and then add the files to your repo using git:

- -
    -
  1. Copy your Django application into this folder (all the files at the same level as manage.py and below, not their containing locallibrary folder).
  2. -
  3. Open the .gitignore file, copy the following lines into the bottom of it, and then save (this file is used to identify files that should not be uploaded to git by default). -
    # Text backup files
    -*.bak
    -
    -#Database
    -*.sqlite3
    -
  4. -
  5. Open a command prompt/terminal and use the add command to add all files to git. -
    git add -A
    -
    -
  6. -
  7. Use the status command to check all files that you are about to add are correct (you want to include source files, not binaries, temporary files etc.). It should look a bit like the listing below. -
    > git status
    -On branch master
    -Your branch is up-to-date with 'origin/master'.
    -Changes to be committed:
    -  (use "git reset HEAD <file>..." to unstage)
    -
    -        modified:   .gitignore
    -        new file:   catalog/__init__.py
    -        ...
    -        new file:   catalog/migrations/0001_initial.py
    -        ...
    -        new file:   templates/registration/password_reset_form.html
    -
  8. -
  9. When you're satisfied commit the files to your local repository: -
    git commit -m "First version of application moved into github"
    -
  10. -
  11. Then synchronise your local repository to the Github website, using the following: -
    git push origin master
    -
  12. -
- -

When this operation completes, you should be able to go back to the page on Github where you created your repo, refresh the page, and see that your whole application has now been uploaded. You can continue to update your repository as files change using this add/commit/push cycle.

- -
-

Tip: This is a good point to make a backup of your "vanilla" project — while some of the changes we're going to be making in the following sections might be useful for deployment on any platform (or development) others might not.

- -

The best way to do this is to use git to manage your revisions. With git you can not only go back to a particular old version, but you can maintain this in a separate "branch" from your production changes and cherry-pick any changes to move between production and development branches. Learning Git is well worth the effort, but is beyond the scope of this topic.

- -

The easiest way to do this is to just copy your files into another location. Use whichever approach best matches your knowledge of git!

-
- -

Update the app for Heroku

- -

This section explains the changes you'll need to make to our LocalLibrary application to get it to work on Heroku. While Heroku's Getting Started on Heroku with Django instructions assume you will use the Heroku client to also run your local development environment, our changes here are compatible with the existing Django development server and ways of working we've already learned.

- -

Procfile

- -

Create the file Procfile (no extension) in the root of your GitHub repository to declare the application's process types and entry points. Copy the following text into it:

- -
web: gunicorn locallibrary.wsgi --log-file -
- -

The "web:" tells Heroku that this is a web dyno and can be sent HTTP traffic. The process to start in this dyno is gunicorn, which is a popular web application server that Heroku recommends. We start Gunicorn using the configuration information in the module locallibrary.wsgi (created with our application skeleton: /locallibrary/wsgi.py).

- -

Gunicorn

- -

Gunicorn is the recommended HTTP server for use with Django on Heroku (as referenced in the Procfile above). It is a pure-Python HTTP server for WSGI applications that can run multiple Python concurrent processes within a single dyno (see Deploying Python applications with Gunicorn for more information).

- -

While we won't need Gunicorn to serve our LocalLibrary application during development, we'll install it so that it becomes part of our requirements for Heroku to set up on the remote server.

- -

Install Gunicorn locally on the command line using pip (which we installed when setting up the development environment):

- -
pip3 install gunicorn
-
- -

Database configuration

- -

We can't use the default SQLite database on Heroku because it is file-based, and it would be deleted from the ephemeral file system every time the application restarts (typically once a day, and every time the application or its configuration variables are changed).

- -

The Heroku mechanism for handling this situation is to use a database add-on and configure the web application using information from an environment configuration variable, set by the add-on. There are quite a lot of database options, but we'll use the hobby tier of the Heroku postgres database as this is free, supported by Django, and automatically added to our new Heroku apps when using the free hobby dyno plan tier.

- -

The database connection information is supplied to the web dyno using a configuration variable named DATABASE_URL. Rather than hard-coding this information into Django, Heroku recommends that developers use the dj-database-url package to parse the DATABASE_URL environment variable and automatically convert it to Django’s desired configuration format. In addition to installing the dj-database-url package we'll also need to install psycopg2, as Django needs this to interact with Postgres databases.

- -
dj-database-url (Django database configuration from environment variable)
- -

Install dj-database-url locally so that it becomes part of our requirements for Heroku to set up on the remote server:

- -
$ pip3 install dj-database-url
-
- -
settings.py
- -

Open /locallibrary/settings.py and copy the following configuration into the bottom of the file:

- -
# Heroku: Update database configuration from $DATABASE_URL.
-import dj_database_url
-db_from_env = dj_database_url.config(conn_max_age=500)
-DATABASES['default'].update(db_from_env)
- -
-

Note:

- -
    -
  • We'll still be using SQLite during development because the DATABASE_URL environment variable will not be set on our development computer.
  • -
  • The value conn_max_age=500 makes the connection persistent, which is far more efficient than recreating the connection on every request cycle. However, this is optional and can be removed if needed.
  • -
-
- -
psycopg2 (Python Postgres database support)
- -

Django needs psycopg2 to work with Postgres databases and you will need to add this to the requirements.txt for Heroku to set this up on the remote server (as discussed in the requirements section below).

- -

Django will use our SQLite database locally by default, because the DATABASE_URL environment variable isn't set in our local environment. If you want to switch to Postgres completely and use our Heroku free tier database for both development and production then you can. For example, to install psycopg2 and its dependencies locally on a Linux-based system you would use the following bash/terminal commands:

- -
sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib
-pip3 install psycopg2
-
- -

Installation instructions for the other platforms can be found on the psycopg2 website here.

- -

However, you don't need to do this — you don't need PostGreSQL active on the local computer, as long as you give it to Heroku as a requirement, in requirements.txt (see below).

- -

Serving static files in production

- -

During development we used Django and the Django development web server to serve our static files (CSS, JavaScript, etc.). In a production environment we instead typically serve static files from a content delivery network (CDN) or the web server.

- -
-

Note: Serving static files via Django/web application is inefficient because the requests have to pass through unnecessary additional code (Django) rather than being handled directly by the web server or a completely separate CDN. While this doesn't matter for local use during development, it would have a significant performance impact if we were to use the same approach in production.

-
- -

To make it easy to host static files separately from the Django web application, Django provides the collectstatic tool to collect these files for deployment (there is a settings variable that defines where the files should be collected when collectstatic is run). Django templates refer to the hosting location of the static files relative to a settings variable (STATIC_URL), so that this can be changed if the static files are moved to another host/server.

- -

The relevant setting variables are:

- -
    -
  • STATIC_URL: This is the base URL location from which static files will be served, for example on a CDN. This is used for the static template variable that is accessed in our base template (see Django Tutorial Part 5: Creating our home page).
  • -
  • STATIC_ROOT: This is the absolute path to a directory where Django's "collectstatic" tool will gather any static files referenced in our templates. Once collected, these can then be uploaded as a group to wherever the files are to be hosted.
  • -
  • STATICFILES_DIRS: This lists additional directories that Django's collectstatic tool should search for static files.
  • -
- -
settings.py
- -

Open /locallibrary/settings.py and copy the following configuration into the bottom of the file. The BASE_DIR should already have been defined in your file (the STATIC_URL may already have been defined within the file when it was created. While it will cause no harm, you might as well delete the duplicate previous reference).

- -
# Static files (CSS, JavaScript, Images)
-# https://docs.djangoproject.com/en/2.0/howto/static-files/
-
-# The absolute path to the directory where collectstatic will collect static files for deployment.
-STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
-
-# The URL to use when referring to static files (where they will be served from)
-STATIC_URL = '/static/'
-
- -

We'll actually do the file serving using a library called WhiteNoise, which we install and configure in the next section.

- -

For more information, see Django and Static Assets (Heroku docs).

- -

Whitenoise

- -

There are many ways to serve static files in production (we saw the relevant Django settings in the previous sections). Heroku recommends using the WhiteNoise project for serving of static assets directly from Gunicorn in production.

- -
-

Note: Heroku automatically calls collectstatic and prepares your static files for use by WhiteNoise after it uploads your application. Check out WhiteNoise documentation for an explanation of how it works and why the implementation is a relatively efficient method for serving these files.

-
- -

The steps to set up WhiteNoise to use with the project are:

- -
WhiteNoise
- -

Install whitenoise locally using the following command:

- -
$ pip3 install whitenoise
-
- -
settings.py
- -

To install WhiteNoise into your Django application, open /locallibrary/settings.py, find the MIDDLEWARE setting and add the WhiteNoiseMiddleware near the top of the list, just below the SecurityMiddleware:

- -
MIDDLEWARE = [
-    'django.middleware.security.SecurityMiddleware',
-    'whitenoise.middleware.WhiteNoiseMiddleware',
-    'django.contrib.sessions.middleware.SessionMiddleware',
-    'django.middleware.common.CommonMiddleware',
-    'django.middleware.csrf.CsrfViewMiddleware',
-    'django.contrib.auth.middleware.AuthenticationMiddleware',
-    'django.contrib.messages.middleware.MessageMiddleware',
-    'django.middleware.clickjacking.XFrameOptionsMiddleware',
-]
-
- -

Optionally, you can reduce the size of the static files when they are served (this is more efficient). Just add the following to the bottom of /locallibrary/settings.py:

- -
# Simplified static file serving.
-# https://warehouse.python.org/project/whitenoise/
-STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
-
- -

Requirements

- -

The Python requirements of your web application must be stored in a file requirements.txt in the root of your repository. Heroku will then install these automatically when it rebuilds your environment. You can create this file using pip on the command line (run the following in the repo root):

- -
pip3 freeze > requirements.txt
- -

After installing all the different dependencies above, your requirements.txt file should have at least these items listed (though the version numbers may be different). Please delete any other dependencies not listed below, unless you've explicitly added them for this application.

- -
dj-database-url==0.4.1
-Django==2.0
-gunicorn==19.6.0
-psycopg2==2.6.2
-whitenoise==3.2.2
-
- -
-

Make sure that a psycopg2 line like the one above is present! Even iIf you didn't install this locally then you should still add this to the requirements.txt.

-
- -

Runtime

- -

The runtime.txt file, if defined, tells Heroku which programming language to use. Create the file in the root of the repo and add the following text:

- -
python-3.6.4
- -
-

Note: Heroku only supports a small number of Python runtimes (at time of writing, this includes the one above). Heroku will use a supported runtime irrespective of the value specified in this file.

-
- -

Save changes to Github and re-test

- -

Next lets save all our changes to Github. In the terminal (whist inside our repository), enter the following commands:

- -
git add -A
-git commit -m "Added files and changes required for deployment to heroku"
-git push origin master
- -

Before we proceed, lets test the site again locally and make sure it wasn't affected by any of our changes above. Run the development web server as usual and then check the site still works as you expect on your browser.

- -
python3 manage.py runserver
- -

We should now be ready to start deploying LocalLibrary on Heroku.

- -

Get a Heroku account

- -

To start using Heroku you will first need to create an account:

- -
    -
  • Go to www.heroku.com and click the SIGN UP FOR FREE button.
  • -
  • Enter your details and then press CREATE FREE ACCOUNT. You'll be asked to check your account for a sign-up email.
  • -
  • Click the account activation link in the signup email. You'll be taken back to your account on the web browser.
  • -
  • Enter your password and click SET PASSWORD AND LOGIN.
  • -
  • You'll then be logged in and taken to the Heroku dashboard: https://dashboard.heroku.com/apps.
  • -
- -

Install the client

- -

Download and install the Heroku client by following the instructions on Heroku here.

- -

After the client is installed you will be able run commands. For example to get help on the client:

- -
heroku help
-
- -

Create and upload the website

- -

To create the app we run the "create" command in the root directory of our repository. This creates a git remote ("pointer to a remote repository") named heroku in our local git environment.

- -
heroku create
- -
-

Note: You can name the remote if you like by specifying a value after "create". If you don't then you'll get a random name. The name is used in the default URL.

-
- -

We can then push our app to the Heroku repository as shown below. This will upload the app, package it in a dyno, run collectstatic, and start the site.

- -
git push heroku master
- -

If we're lucky, the app is now "running" on the site, but it won't be working properly because we haven't set up the database tables for use by our application. To do this we need to use the heroku run command and start a "one off dyno" to perform a migrate operation. Enter the following command in your terminal:

- -
heroku run python manage.py migrate
- -

We're also going to need to be able to add books and authors, so lets also create our administration superuser, again using a one-off dyno:

- -
heroku run python manage.py createsuperuser
- -

Once this is complete, we can look at the site. It should work, although it won't have any books in it yet. To open your browser to the new website, use the command:

- -
heroku open
- -

Create some books in the admin site, and check out whether the site is behaving as you expect.

- -

Managing addons

- -

You can check out the add-ons to your app using the heroku addons command. This will list all addons, and their price tier and state.

- -
>heroku addons
-
-Add-on                                     Plan       Price  State
-─────────────────────────────────────────  ─────────  ─────  ───────
-heroku-postgresql (postgresql-flat-26536)  hobby-dev  free   created
- └─ as DATABASE
- -

Here we see that we have just one add-on, the postgres SQL database. This is free, and was created automatically when we created the app. You can open a web page to examine the database add-on (or any other add-on) in more detail using the following command:

- -
heroku addons:open heroku-postgresql
-
- -

Other commands allow you to create, destroy, upgrade and downgrade addons (using a similar syntax to opening). For more information see Managing Add-ons (Heroku docs).

- -

Setting configuration variables

- -

You can check out the configuration variables for the site using the heroku config command. Below you can see that we have just one variable, the DATABASE_URL used to configure our database.

- -
>heroku config
-
-=== locallibrary Config Vars
-DATABASE_URL: postgres://uzfnbcyxidzgrl:j2jkUFDF6OGGqxkgg7Hk3ilbZI@ec2-54-243-201-144.compute-1.amazonaws.com:5432/dbftm4qgh3kda3
- -

If you recall from the section on getting the website ready to publish, we have to set environment variables for DJANGO_SECRET_KEY and DJANGO_DEBUG. Let's do this now.

- -
-

Note: The secret key needs to be really secret! One way to generate a new key is to create a new Django project (django-admin startproject someprojectname) and then get the key that is generated for you from its settings.py.

-
- -

We set DJANGO_SECRET_KEY using the config:set command (as shown below). Remember to use your own secret key!

- -
>heroku config:set DJANGO_SECRET_KEY=eu09(ilk6@4sfdofb=b_2ht@vad*$ehh9-)3u_83+y%(+phh&=
-
-Setting DJANGO_SECRET_KEY and restarting locallibrary... done, v7
-DJANGO_SECRET_KEY: eu09(ilk6@4sfdofb=b_2ht@vad*$ehh9-)3u_83+y%(+phh
-
- -

We similarly set DJANGO_DEBUG:

- -
>heroku config:set DJANGO_DEBUG=
-
-Setting DJANGO_DEBUG and restarting locallibrary... done, v8
- -

If you visit the site now you'll get a "Bad request" error, because the ALLOWED_HOSTS setting is required if you have DEBUG=False (as a security measure). Open /locallibrary/settings.py and change the ALLOWED_HOSTS setting to include your base app url (e.g. 'locallibrary1234.herokuapp.com') and the URL you normally use on your local development server.

- -
ALLOWED_HOSTS = ['<your app URL without the https:// prefix>.herokuapp.com','127.0.0.1']
-# For example:
-# ALLOWED_HOSTS = ['fathomless-scrubland-30645.herokuapp.com','127.0.0.1']
-
- -

Then save your settings and commit them to your Github repo and to Heroku:

- -
git add -A
-git commit -m 'Update ALLOWED_HOSTS with site and development server URL'
-git push origin master
-git push heroku master
- -
-

After the site update to Heroku completes, enter an URL that does not exist (e.g. /catalog/doesnotexist/). Previously this would have displayed a detailed debug page, but now you should just see a simple "Not Found" page.

-
- -

Debugging

- -

The Heroku client provides a few tools for debugging:

- -
heroku logs  # Show current logs
-heroku logs --tail # Show current logs and keep updating with any new results
-heroku config:set DEBUG_COLLECTSTATIC=1 # Add additional logging for collectstatic (this tool is run automatically during a build)
-heroku ps   #Display dyno status
-
- -

If you need more information than these can provide you will need to start looking into Django Logging.

- -
    -
- -

Summary

- -

That's the end of this tutorial on setting up Django apps in production, and also the series of tutorials on working with Django. We hope you've found them useful. You can check out a fully worked-through version of the source code on Github here.
-
- The next step is to read our last few articles, and then complete the assessment task.

- -

See also

- - - -

{{PreviousMenuNext("Learn/Server-side/Django/Testing", "Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}}

- -

- -

In this module

- - - -

diff --git a/files/zh-tw/learn/server-side/django/deployment/index.md b/files/zh-tw/learn/server-side/django/deployment/index.md new file mode 100644 index 00000000000000..0068b8258f456c --- /dev/null +++ b/files/zh-tw/learn/server-side/django/deployment/index.md @@ -0,0 +1,643 @@ +--- +title: 'Django Tutorial Part 11: Deploying Django to production' +slug: Learn/Server-side/Django/Deployment +translation_of: Learn/Server-side/Django/Deployment +--- +{{LearnSidebar}}{{PreviousMenuNext("Learn/Server-side/Django/Testing", "Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}} + +現在,您已經創建(並測試)了一個令人敬畏的 [LocalLibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) 網站,如果您希望將其安裝在公共 Web 服務器上,以便圖書館工作人員、和成員,可以通過 Internet 訪問它。本文概述如何找到主機來部署您的網站,以及您需要做什麼,才能讓您的網站準備好生產環境。 + + + + + + + + + + + + +
Prerequisites: + Complete all previous tutorial topics, including + Django Tutorial Part 10: Testing a Django web application. +
Objective:To learn where and how you can deploy a Django app to production.
+ +## Overview + +Once your site is finished (or finished "enough" to start public testing) you're going to need to host it somewhere more public and accessible than your personal development computer. + +Up to now you've been working in a development environment, using the Django development web server to share your site to the local browser/network, and running your website with (insecure) development settings that expose debug and other private information. Before you can host a website externally you're first going to have to: + +- Make a few changes to your project settings. +- Choose an environment for hosting the Django app. +- Choose an environment for hosting any static files. +- Set up a production-level infrastructure for serving your website. + +This tutorial provides some guidance on your options for choosing a hosting site, a brief overview of what you need to do in order to get your Django app ready for production, and a worked example of how to install the LocalLibrary website onto the [Heroku](https://www.heroku.com/) cloud hosting service. + +## What is a production environment? + +The production environment is the environment provided by the server computer where you will run your website for external consumption. The environment includes: + +- Computer hardware on which the website runs. +- Operating system (e.g. Linux, Windows). +- Programming language runtime and framework libraries on top of which your website is written. +- Web server used to serve pages and other content (e.g. Nginx, Apache). +- Application server that passes "dynamic" requests between your Django website and the webserver. +- Databases on which your website is dependent. + +> **備註:** Depending on how your production is configured you might also have a reverse proxy, load balancer, etc. + +The server computer could be located on your premises and connected to the Internet by a fast link, but it is far more common to use a computer that is hosted "in the cloud". What this actually means is that your code is run on some remote computer (or possibly a "virtual" computer) in your hosting company's data center(s). The remote server will usually offer some guaranteed level of computing resources (e.g. CPU, RAM, storage memory, etc.) and Internet connectivity for a certain price. + +This sort of remotely accessible computing/networking hardware is referred to as _Infrastructure as a Service (IaaS)_. Many IaaS vendors provide options to preinstall a particular operating system, onto which you must install the other components of your production environment. Other vendors allow you to select more fully-featured environments, perhaps including a complete Django and web-server setup. + +> **備註:** Pre-built environments can make setting up your website very easy because they reduce the configuration, but the available options may limit you to an unfamiliar server (or other components) and may be based on an older version of the OS. Often it is better to install components yourself, so that you get the ones that you want, and when you need to upgrade parts of the system, you have some idea where to start! + +Other hosting providers support Django as part of a _Platform as a Service_ (PaaS) offering. In this sort of hosting you don't need to worry about most of your production environment (web server, application server, load balancers) as the host platform takes care of those for you (along with most of what you need to do in order to scale your application). That makes deployment quite easy, because you just need to concentrate on your web application and not all the other server infrastructure. + +Some developers will choose the increased flexibility provided by IaaS over PaaS, while others will appreciate the reduced maintenance overhead and easier scaling of PaaS. When you're getting started, setting up your website on a PaaS system is much easier, and so that is what we'll do in this tutorial. + +> **備註:** If you choose a Python/Django-friendly hosting provider they should provide instructions on how to set up a Django website using different configurations of webserver, application server, reverse proxy, etc (this won't be relevant if you choose a PaaS). For example, there are many step-by-step guides for various configurations in the [Digital Ocean Django community docs](https://www.digitalocean.com/community/tutorials?q=django). + +## Choosing a hosting provider + +There are well over 100 hosting providers that are known to either actively support or work well with Django (you can find a fairly extensive list at [Djangofriendly hosts](http://djangofriendly.com/hosts/)). These vendors provide different types of environments (IaaS, PaaS), and different levels of computing and network resources at different prices. + +Some of the things to consider when choosing a host: + +- How busy your site is likely to be and the cost of data and computing resources required to meet that demand. +- Level of support for scaling horizontally (adding more machines) and vertically (upgrading to more powerful machines) and the costs of doing so. +- Where the supplier has data centres, and hence where access is likely to be fastest. +- The host's historical uptime and downtime performance. +- Tools provided for managing the site — are they easy to use and are they secure (e.g. SFTP vs FTP). +- Inbuilt frameworks for monitoring your server. +- Known limitations. Some hosts will deliberately block certain services (e.g. email) . Others offer only a certain number of hours of "live time" in some price tiers, or only offer a small amount of storage. +- Additional benefits. Some providers will offer free domain names and support for SSL certificates that you would otherwise have to pay for. +- Whether the "free" tier you're relying on expires over time, and whether the cost of migrating to a more expensive tier means you would have been better off using some other service in the first place! + +The good news when you're starting out is that there are quite a few sites that provide "evaluation", "developer", or "hobbyist" computing environments for "free". These are always fairly resource constrained/limited environments, and you do need to be aware that they may expire after some introductory period. They are however great for testing low traffic sites in a real environment, and can provide an easy migration to paying for more resources when your site gets busier. Popular choices in this category include [Heroku](https://www.heroku.com/), [Python Anywhere](https://www.pythonanywhere.com/), [Amazon Web Services](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html), [Microsoft Azure](https://azure.microsoft.com/en-us/pricing/details/app-service/), etc. + +Many providers also have a "basic" tier that provides more useful levels of computing power and fewer limitations. [Digital Ocean](https://www.digitalocean.com/) and [Python Anywhere](https://www.pythonanywhere.com/) are examples of popular hosting providers that offer a relatively inexpensive basic computing tier (in the $5 to $10USD per month range). + +> **備註:** Remember that price is not the only selection criteria. If your website is successful, it may turn out that scalability is the most important consideration. + +## Getting your website ready to publish + +The [Django skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) created using the _django-admin_ and _manage.py_ tools are configured to make development easier. Many of the Django project settings (specified in **settings.py**) should be different for production, either for security or performance reasons. + +> **備註:** It is common to have a separate **settings.py** file for production, and to import sensitive settings from a separate file or an environment variable. This file should then be protected, even if the rest of the source code is available on a public repository. + +The critical settings that you must check are: + +- `DEBUG`. This should be set as `False` in production (`DEBUG = False`). This stops the sensitive/confidential debug trace and variable information from being displayed. +- `SECRET_KEY`. This is a large random value used for CSRF protection etc. It is important that the key used in production is not in source control or accessible outside the production server. The Django documents suggest that this might best be loaded from an environment variable or read from a serve-only file. + + # Read SECRET_KEY from an environment variable + import os + SECRET_KEY = os.environ['SECRET_KEY'] + + #OR + + #Read secret key from a file + with open('/etc/secret_key.txt') as f: + SECRET_KEY = f.read().strip() + +Let's change the _LocalLibrary_ application so that we read our `SECRET_KEY` and `DEBUG` variables from environment variables if they are defined, but otherwise use the default values in the configuration file. + +Open **/locallibrary/settings.py**, disable the original `SECRET_KEY` configuration and add the new lines as shown below in **bold**. During development no environment variable will be specified for the key, so the default value will be used (it shouldn't matter what key you use here, or if the key "leaks", because you won't use it in production). + +```python +# SECURITY WARNING: keep the secret key used in production secret! +# SECRET_KEY = 'cg#p$g+j9tax!#a3cup@1$8obt2_+&k3q+pmu)5%asj6yjpkag' +import os +SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'cg#p$g+j9tax!#a3cup@1$8obt2_+&k3q+pmu)5%asj6yjpkag') +``` + +Then comment out the existing `DEBUG` setting and add the new line shown below. + +```python +# SECURITY WARNING: don't run with debug turned on in production! +# DEBUG = True +DEBUG = bool( os.environ.get('DJANGO_DEBUG', True) ) +``` + +The value of the `DEBUG` will be `True` by default, but will be `False` if the value of the `DJANGO_DEBUG` environment variable is set to an empty string, e.g. `DJANGO_DEBUG=''`. + +> **備註:** It would be more intuitive if we could just set and unset the `DJANGO_DEBUG` environment variable to `True` and `False` directly, rather than using "any string" or "empty string" (respectively). Unfortunately environment variable values are stored as Python strings, and the only string that evaluates as `False` is the empty string (e.g. `bool('')==False`). + +A full checklist of settings you might want to change is provided in [Deployment checklist](https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/) (Django docs). You can also list a number of these using the terminal command below: + +```python +python3 manage.py check --deploy +``` + +## Example: Installing LocalLibrary on Heroku + +This section provides a practical demonstration of how to install _LocalLibrary_ on the [Heroku PaaS cloud](http://heroku.com). + +### Why Heroku? + +Heroku is one of the longest running and popular cloud-based PaaS services. It originally supported only Ruby apps, but now can be used to host apps from many programming environments, including Django! + +We are choosing to use Heroku for several reasons: + +- Heroku has a [free tier](https://www.heroku.com/pricing) that is _really_ free (albeit with some limitations). +- As a PaaS, Heroku takes care of a lot of the web infrastructure for us. This makes it much easier to get started, because you don't worry about servers, load balancers, reverse proxies, or any of the other web infrastructure that Heroku provides for us under the hood. +- While it does have some limitations these will not affect this particular application. For example: + + - Heroku provides only short-lived storage so user-uploaded files cannot safely be stored on Heroku itself. + - The free tier will sleep an inactive web app if there are no requests within a half hour period. The site may then take several seconds to respond when it is woken up. + - The free tier limits the time that your site is running to a certain amount of hours every month (not including the time that the site is "asleep"). This is fine for a low use/demonstration site, but will not be suitable if 100% uptime is required. + - Other limitations are listed in [Limits](https://devcenter.heroku.com/articles/limits) (Heroku docs). + +- Mostly it just works, and if you end up loving it, scaling your app is very easy. + +While Heroku is perfect for hosting this demonstration it may not be perfect for your real website. Heroku makes things easy to set up and scale, at the cost of being less flexible, and potentially a lot more expensive once you get out of the free tier. + +### How does Heroku work? + +Heroku runs Django websites within one or more "[Dynos](https://devcenter.heroku.com/articles/dynos)", which are isolated, virtualized Unix containers that provide the environment required to run an application. The dynos are completely isolated and have an _ephemeral_ file system (a short-lived file system that is cleaned/emptied every time the dyno restarts). The only thing that dynos share by default are application [configuration variables](https://devcenter.heroku.com/articles/config-vars). Heroku internally uses a load balancer to distribute web traffic to all "web" dynos. Since nothing is shared between them, Heroku can scale an app horizontally simply by adding more dynos (though of course you may also need to scale your database to accept additional connections). + +Because the file system is ephemeral you can't install services required by your application directly (e.g. databases, queues, caching systems, storage, email services, etc). Instead Heroku web applications use backing services provided as independent "add-ons" by Heroku or 3rd parties. Once attached to your web application, the dynos access the services using information contained in application configuration variables. + +In order to execute your application Heroku needs to be able to set up the appropriate environment and dependencies, and also understand how it is launched. For Django apps we provide this information in a number of text files: + +- **runtime.txt**: the programming language and version to use. +- **requirements.txt**: the Python component dependencies, including Django. +- **Procfile**: A list of processes to be executed to start the web application. For Django this will usually be the Gunicorn web application server (with a `.wsgi` script). +- **wsgi.py**: [WSGI](http://wsgi.readthedocs.io/en/latest/what.html) configuration to call our Django application in the Heroku environment. + +Developers interact with Heroku using a special client app/terminal, which is much like a Unix bash script. This allows you to upload code that is stored in a git repository, inspect the running processes, see logs, set configuration variables and much more! + +In order to get our application to work on Heroku we'll need to put our Django web application into a git repository, add the files above, integrate with a database add-on, and make changes to properly handle static files. + +Once we've done all that we can set up a Heroku account, get the Heroku client, and use it to install our website. + +> **備註:** The instructions below reflect how to work with Heroku at time of writing. If Heroku significantly change their processes, you may wish to instead check their setup documents: [Getting Started on Heroku with Django](https://devcenter.heroku.com/articles/getting-started-with-python#introduction). + +That's all the overview you need in order to get started (see [How Heroku works](https://devcenter.heroku.com/articles/how-heroku-works) for a more comprehensive guide). + +### Creating an application repository in Github + +Heroku is closely integrated with the **git** source code version control system, using it to upload/synchronise any changes you make to the live system. It does this by adding a new heroku "remote" repository named _heroku_ pointing to a repository for your source on the Heroku cloud. During development you use git to store changes on your "master" repository. When you want to deploy your site, you sync your changes to the Heroku repository. + +> **備註:** If you're used to following good software development practices you are probably already using git or some other SCM system. If you already have a git repository, then you can skip this step. + +There are a lot of ways of to work with git, but one of the easiest is to first set up an account on [Github](https://github.com/), create the repository there, and then sync to it locally: + +1. Visit and create an account. +2. Once you are logged in, click the **+** link in the top toolbar and select **New repository**. +3. Fill in all the fields on this form. While these are not compulsory, they are strongly recommended. + + - Enter a new repository name (e.g. _django_local_library_), and description (e.g. "Local Library website written in Django". + - Choose **Python** in the _Add .gitignore_ selection list. + - Choose your preferred license in the _Add license_ selection list. + - Check **Initialize this repository with a README**. + +4. Press **Create repository**. +5. Click the green "**Clone or download**" button on your new repo page. +6. Copy the URL value from the text field inside the dialog box that appears (it should be something like: **https\://github.com/_\_/django_local_library.git**). + +Now the repository ("repo") is created we are going to want to clone it on our local computer: + +1. Install _git_ for your local computer (you can find versions for different platforms [here](https://git-scm.com/downloads)). +2. Open a command prompt/terminal and clone your repository using the URL you copied above: + + ```bash + git clone https://github.com//django_local_library.git + ``` + + This will create the repository below the current point. + +3. Navigate into the new repo. + + ```bash + cd django_local_library.git + ``` + +The final step is to copy in your application and then add the files to your repo using git: + +1. Copy your Django application into this folder (all the files at the same level as **manage.py** and below, **not** their containing locallibrary folder). +2. Open the **.gitignore** file, copy the following lines into the bottom of it, and then save (this file is used to identify files that should not be uploaded to git by default). + + # Text backup files + *.bak + + #Database + *.sqlite3 + +3. Open a command prompt/terminal and use the `add` command to add all files to git. + + ```bash + git add -A + ``` + +4. Use the status command to check all files that you are about to add are correct (you want to include source files, not binaries, temporary files etc.). It should look a bit like the listing below. + + > git status + On branch master + Your branch is up-to-date with 'origin/master'. + Changes to be committed: + (use "git reset HEAD ..." to unstage) + + modified: .gitignore + new file: catalog/__init__.py + ... + new file: catalog/migrations/0001_initial.py + ... + new file: templates/registration/password_reset_form.html + +5. When you're satisfied commit the files to your local repository: + + ```bash + git commit -m "First version of application moved into github" + ``` + +6. Then synchronise your local repository to the Github website, using the following: + + git push origin master + +When this operation completes, you should be able to go back to the page on Github where you created your repo, refresh the page, and see that your whole application has now been uploaded. You can continue to update your repository as files change using this add/commit/push cycle. + +> **備註:** This is a good point to make a backup of your "vanilla" project — while some of the changes we're going to be making in the following sections might be useful for deployment on any platform (or development) others might not. +> +> The _best_ way to do this is to use _git_ to manage your revisions. With _git_ you can not only go back to a particular old version, but you can maintain this in a separate "branch" from your production changes and cherry-pick any changes to move between production and development branches. [Learning Git](https://help.github.com/articles/good-resources-for-learning-git-and-github/) is well worth the effort, but is beyond the scope of this topic. +> +> The _easiest_ way to do this is to just copy your files into another location. Use whichever approach best matches your knowledge of git! + +### Update the app for Heroku + +This section explains the changes you'll need to make to our _LocalLibrary_ application to get it to work on Heroku. While Heroku's [Getting Started on Heroku with Django](https://devcenter.heroku.com/articles/getting-started-with-python#introduction) instructions assume you will use the Heroku client to also run your local development environment, our changes here are compatible with the existing Django development server and ways of working we've already learned. + +#### Procfile + +Create the file `Procfile` (no extension) in the root of your GitHub repository to declare the application's process types and entry points. Copy the following text into it: + + web: gunicorn locallibrary.wsgi --log-file - + +The "`web:`" tells Heroku that this is a web dyno and can be sent HTTP traffic. The process to start in this dyno is _gunicorn_, which is a popular web application server that Heroku recommends. We start Gunicorn using the configuration information in the module `locallibrary.wsgi` (created with our application skeleton: **/locallibrary/wsgi.py**). + +#### Gunicorn + +[Gunicorn](http://gunicorn.org/) is the recommended HTTP server for use with Django on Heroku (as referenced in the Procfile above). It is a pure-Python HTTP server for WSGI applications that can run multiple Python concurrent processes within a single dyno (see [Deploying Python applications with Gunicorn](https://devcenter.heroku.com/articles/python-gunicorn) for more information). + +While we won't need _Gunicorn_ to serve our LocalLibrary application during development, we'll install it so that it becomes part of our [requirements](#requirements) for Heroku to set up on the remote server. + +Install _Gunicorn_ locally on the command line using _pip_ (which we installed when [setting up the development environment](/en-US/docs/Learn/Server-side/Django/development_environment)): + +```bash +pip3 install gunicorn +``` + +#### Database configuration + +We can't use the default SQLite database on Heroku because it is file-based, and it would be deleted from the _ephemeral_ file system every time the application restarts (typically once a day, and every time the application or its configuration variables are changed). + +The Heroku mechanism for handling this situation is to use a [database add-on](https://elements.heroku.com/addons#data-stores) and configure the web application using information from an environment [configuration variable](https://devcenter.heroku.com/articles/config-vars), set by the add-on. There are quite a lot of database options, but we'll use the [hobby tier](https://devcenter.heroku.com/articles/heroku-postgres-plans#plan-tiers) of the _Heroku postgres_ database as this is free, supported by Django, and automatically added to our new Heroku apps when using the free hobby dyno plan tier. + +The database connection information is supplied to the web dyno using a configuration variable named `DATABASE_URL`. Rather than hard-coding this information into Django, Heroku recommends that developers use the [dj-database-url](https://warehouse.python.org/project/dj-database-url/) package to parse the `DATABASE_URL` environment variable and automatically convert it to Django’s desired configuration format. In addition to installing the _dj-database-url_ package we'll also need to install [psycopg2](http://initd.org/psycopg/), as Django needs this to interact with Postgres databases. + +##### dj-database-url (Django database configuration from environment variable) + +Install _dj-database-url_ locally so that it becomes part of our [requirements](#requirements) for Heroku to set up on the remote server: + + $ pip3 install dj-database-url + +##### settings.py + +Open **/locallibrary/settings.py** and copy the following configuration into the bottom of the file: + + # Heroku: Update database configuration from $DATABASE_URL. + import dj_database_url + db_from_env = dj_database_url.config(conn_max_age=500) + DATABASES['default'].update(db_from_env) + +> **備註:** +> +> - We'll still be using SQLite during development because the `DATABASE_URL` environment variable will not be set on our development computer. +> - The value `conn_max_age=500` makes the connection persistent, which is far more efficient than recreating the connection on every request cycle. However, this is optional and can be removed if needed. + +##### psycopg2 (Python Postgres database support) + +Django needs _psycopg2_ to work with Postgres databases and you will need to add this to the [requirements.txt](#requirements) for Heroku to set this up on the remote server (as discussed in the requirements section below). + +Django will use our SQLite database locally by default, because the `DATABASE_URL` environment variable isn't set in our local environment. If you want to switch to Postgres completely and use our Heroku free tier database for both development and production then you can. For example, to install psycopg2 and its dependencies locally on a Linux-based system you would use the following bash/terminal commands: + +```bash +sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib +pip3 install psycopg2 +``` + +Installation instructions for the other platforms can be found on the [psycopg2 website here](http://initd.org/psycopg/docs/install.html). + +However, you don't need to do this — you don't need PostGreSQL active on the local computer, as long as you give it to Heroku as a requirement, in `requirements.txt` (see below). + +#### Serving static files in production + +During development we used Django and the Django development web server to serve our static files (CSS, JavaScript, etc.). In a production environment we instead typically serve static files from a content delivery network (CDN) or the web server. + +> **備註:** Serving static files via Django/web application is inefficient because the requests have to pass through unnecessary additional code (Django) rather than being handled directly by the web server or a completely separate CDN. While this doesn't matter for local use during development, it would have a significant performance impact if we were to use the same approach in production. + +To make it easy to host static files separately from the Django web application, Django provides the _collectstatic_ tool to collect these files for deployment (there is a settings variable that defines where the files should be collected when _collectstatic_ is run). Django templates refer to the hosting location of the static files relative to a settings variable (`STATIC_URL`), so that this can be changed if the static files are moved to another host/server. + +The relevant setting variables are: + +- `STATIC_URL`: This is the base URL location from which static files will be served, for example on a CDN. This is used for the static template variable that is accessed in our base template (see [Django Tutorial Part 5: Creating our home page](/en-US/docs/Learn/Server-side/Django/Home_page)). +- `STATIC_ROOT`: This is the absolute path to a directory where Django's "collectstatic" tool will gather any static files referenced in our templates. Once collected, these can then be uploaded as a group to wherever the files are to be hosted. +- `STATICFILES_DIRS`: This lists additional directories that Django's collectstatic tool should search for static files. + +##### settings.py + +Open **/locallibrary/settings.py** and copy the following configuration into the bottom of the file. The `BASE_DIR` should already have been defined in your file (the `STATIC_URL` may already have been defined within the file when it was created. While it will cause no harm, you might as well delete the duplicate previous reference). + + # Static files (CSS, JavaScript, Images) + # https://docs.djangoproject.com/en/2.0/howto/static-files/ + + # The absolute path to the directory where collectstatic will collect static files for deployment. + STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') + + # The URL to use when referring to static files (where they will be served from) + STATIC_URL = '/static/' + +We'll actually do the file serving using a library called [WhiteNoise](https://warehouse.python.org/project/whitenoise/), which we install and configure in the next section. + +For more information, see [Django and Static Assets](https://devcenter.heroku.com/articles/django-assets) (Heroku docs). + +#### Whitenoise + +There are many ways to serve static files in production (we saw the relevant Django settings in the previous sections). Heroku recommends using the [WhiteNoise](https://warehouse.python.org/project/whitenoise/) project for serving of static assets directly from Gunicorn in production. + +> **備註:** Heroku automatically calls _collectstatic_ and prepares your static files for use by WhiteNoise after it uploads your application. Check out [WhiteNoise](https://warehouse.python.org/project/whitenoise/) documentation for an explanation of how it works and why the implementation is a relatively efficient method for serving these files. + +The steps to set up _WhiteNoise_ to use with the project are: + +##### WhiteNoise + +Install whitenoise locally using the following command: + + $ pip3 install whitenoise + +##### settings.py + +To install _WhiteNoise_ into your Django application, open **/locallibrary/settings.py**, find the `MIDDLEWARE` setting and add the `WhiteNoiseMiddleware` near the top of the list, just below the `SecurityMiddleware`: + + MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'whitenoise.middleware.WhiteNoiseMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', + ] + +Optionally, you can reduce the size of the static files when they are served (this is more efficient). Just add the following to the bottom of **/locallibrary/settings.py**: + + # Simplified static file serving. + # https://warehouse.python.org/project/whitenoise/ + STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' + +#### Requirements + +The Python requirements of your web application must be stored in a file **requirements.txt** in the root of your repository. Heroku will then install these automatically when it rebuilds your environment. You can create this file using _pip_ on the command line (run the following in the repo root): + +```bash +pip3 freeze > requirements.txt +``` + +After installing all the different dependencies above, your **requirements.txt** file should have _at least_ these items listed (though the version numbers may be different). Please delete any other dependencies not listed below, unless you've explicitly added them for this application. + + dj-database-url==0.4.1 + Django==2.0 + gunicorn==19.6.0 + psycopg2==2.6.2 + whitenoise==3.2.2 + +> **備註:** Make sure that a **psycopg2** line like the one above is present! Even iIf you didn't install this locally then you should still add this to the **requirements.txt**. + +#### Runtime + +The **runtime.txt** file, if defined, tells Heroku which programming language to use. Create the file in the root of the repo and add the following text: + + python-3.6.4 + +> **備註:** Heroku only supports a small number of [Python runtimes](https://devcenter.heroku.com/articles/python-support#supported-python-runtimes) (at time of writing, this includes the one above). Heroku will use a supported runtime irrespective of the value specified in this file. + +#### Save changes to Github and re-test + +Next lets save all our changes to Github. In the terminal (whist inside our repository), enter the following commands: + +```python +git add -A +git commit -m "Added files and changes required for deployment to heroku" +git push origin master +``` + +Before we proceed, lets test the site again locally and make sure it wasn't affected by any of our changes above. Run the development web server as usual and then check the site still works as you expect on your browser. + +```bash +python3 manage.py runserver +``` + +We should now be ready to start deploying LocalLibrary on Heroku. + +### Get a Heroku account + +To start using Heroku you will first need to create an account: + +- Go to [www.heroku.com](https://www.heroku.com/) and click the **SIGN UP FOR FREE** button. +- Enter your details and then press **CREATE FREE ACCOUNT**. You'll be asked to check your account for a sign-up email. +- Click the account activation link in the signup email. You'll be taken back to your account on the web browser. +- Enter your password and click **SET PASSWORD AND LOGIN**. +- You'll then be logged in and taken to the Heroku dashboard: . + +### Install the client + +Download and install the Heroku client by following the [instructions on Heroku here](https://devcenter.heroku.com/articles/getting-started-with-python#set-up). + +After the client is installed you will be able run commands. For example to get help on the client: + +```bash +heroku help +``` + +### Create and upload the website + +To create the app we run the "create" command in the root directory of our repository. This creates a git remote ("pointer to a remote repository") named _heroku_ in our local git environment. + +```bash +heroku create +``` + +> **備註:** You can name the remote if you like by specifying a value after "create". If you don't then you'll get a random name. The name is used in the default URL. + +We can then push our app to the Heroku repository as shown below. This will upload the app, package it in a dyno, run collectstatic, and start the site. + +```bash +git push heroku master +``` + +If we're lucky, the app is now "running" on the site, but it won't be working properly because we haven't set up the database tables for use by our application. To do this we need to use the `heroku run` command and start a "[one off dyno](https://devcenter.heroku.com/articles/deploying-python#one-off-dynos)" to perform a migrate operation. Enter the following command in your terminal: + +```bash +heroku run python manage.py migrate +``` + +We're also going to need to be able to add books and authors, so lets also create our administration superuser, again using a one-off dyno: + +```bash +heroku run python manage.py createsuperuser +``` + +Once this is complete, we can look at the site. It should work, although it won't have any books in it yet. To open your browser to the new website, use the command: + +```bash +heroku open +``` + +Create some books in the admin site, and check out whether the site is behaving as you expect. + +### Managing addons + +You can check out the add-ons to your app using the `heroku addons` command. This will list all addons, and their price tier and state. + +```bash +>heroku addons + +Add-on Plan Price State +───────────────────────────────────────── ───────── ───── ─────── +heroku-postgresql (postgresql-flat-26536) hobby-dev free created + └─ as DATABASE +``` + +Here we see that we have just one add-on, the postgres SQL database. This is free, and was created automatically when we created the app. You can open a web page to examine the database add-on (or any other add-on) in more detail using the following command: + +```bash +heroku addons:open heroku-postgresql +``` + +Other commands allow you to create, destroy, upgrade and downgrade addons (using a similar syntax to opening). For more information see [Managing Add-ons](https://devcenter.heroku.com/articles/managing-add-ons) (Heroku docs). + +### Setting configuration variables + +You can check out the configuration variables for the site using the `heroku config` command. Below you can see that we have just one variable, the `DATABASE_URL` used to configure our database. + +```bash +>heroku config + +=== locallibrary Config Vars +DATABASE_URL: postgres://uzfnbcyxidzgrl:j2jkUFDF6OGGqxkgg7Hk3ilbZI@ec2-54-243-201-144.compute-1.amazonaws.com:5432/dbftm4qgh3kda3 +``` + +If you recall from the section on [getting the website ready to publish](#Getting_your_website_ready_to_publish), we have to set environment variables for `DJANGO_SECRET_KEY` and `DJANGO_DEBUG`. Let's do this now. + +> **備註:** The secret key needs to be really secret! One way to generate a new key is to create a new Django project (`django-admin startproject someprojectname`) and then get the key that is generated for you from its **settings.py**. + +We set `DJANGO_SECRET_KEY` using the `config:set` command (as shown below). Remember to use your own secret key! + +```bash +>heroku config:set DJANGO_SECRET_KEY=eu09(ilk6@4sfdofb=b_2ht@vad*$ehh9-)3u_83+y%(+phh&= + +Setting DJANGO_SECRET_KEY and restarting locallibrary... done, v7 +DJANGO_SECRET_KEY: eu09(ilk6@4sfdofb=b_2ht@vad*$ehh9-)3u_83+y%(+phh +``` + +We similarly set `DJANGO_DEBUG`: + +```bash +>heroku config:set DJANGO_DEBUG= + +Setting DJANGO_DEBUG and restarting locallibrary... done, v8 +``` + +If you visit the site now you'll get a "Bad request" error, because the [ALLOWED_HOSTS](https://docs.djangoproject.com/en/2.0/ref/settings/#allowed-hosts) setting is _required_ if you have `DEBUG=False` (as a security measure). Open **/locallibrary/settings.py** and change the `ALLOWED_HOSTS` setting to include your base app url (e.g. 'locallibrary1234.herokuapp.com') and the URL you normally use on your local development server. + +```python +ALLOWED_HOSTS = ['.herokuapp.com','127.0.0.1'] +# For example: +# ALLOWED_HOSTS = ['fathomless-scrubland-30645.herokuapp.com','127.0.0.1'] +``` + +Then save your settings and commit them to your Github repo and to Heroku: + +```bash +git add -A +git commit -m 'Update ALLOWED_HOSTS with site and development server URL' +git push origin master +git push heroku master +``` + +> **備註:** After the site update to Heroku completes, enter an URL that does not exist (e.g. **/catalog/doesnotexist/**). Previously this would have displayed a detailed debug page, but now you should just see a simple "Not Found" page. + +### Debugging + +The Heroku client provides a few tools for debugging: + +```bash +heroku logs # Show current logs +heroku logs --tail # Show current logs and keep updating with any new results +heroku config:set DEBUG_COLLECTSTATIC=1 # Add additional logging for collectstatic (this tool is run automatically during a build) +heroku ps #Display dyno status +``` + +If you need more information than these can provide you will need to start looking into [Django Logging](https://docs.djangoproject.com/en/2.0/topics/logging/). + +## Summary + +That's the end of this tutorial on setting up Django apps in production, and also the series of tutorials on working with Django. We hope you've found them useful. You can check out a fully worked-through version of the [source code on Github here](https://github.com/mdn/django-locallibrary-tutorial). + +The next step is to read our last few articles, and then complete the assessment task. + +## See also + +- [Deploying Django](https://docs.djangoproject.com/en/2.0/howto/deployment/) (Django docs) + + - [Deployment checklist](https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/) (Django docs) + - [Deploying static files](https://docs.djangoproject.com/en/2.0/howto/static-files/deployment/) (Django docs) + - [How to deploy with WSGI](https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/) (Django docs) + - [How to use Django with Apache and mod_wsgi](https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/modwsgi/) (Django docs) + - [How to use Django with Gunicorn](https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/gunicorn/) (Django docs) + +- Heroku + + - [Configuring Django apps for Heroku](https://devcenter.heroku.com/articles/django-app-configuration) (Heroku docs) + - [Getting Started on Heroku with Django](https://devcenter.heroku.com/articles/getting-started-with-python#introduction) (Heroku docs) + - [Django and Static Assets](https://devcenter.heroku.com/articles/django-assets) (Heroku docs) + - [Concurrency and Database Connections in Django](https://devcenter.heroku.com/articles/python-concurrency-and-database-connections) (Heroku docs) + - [How Heroku works](https://devcenter.heroku.com/articles/how-heroku-works) (Heroku docs) + - [Dynos and the Dyno Manager](https://devcenter.heroku.com/articles/dynos) (Heroku docs) + - [Configuration and Config Vars](https://devcenter.heroku.com/articles/config-vars) (Heroku docs) + - [Limits](https://devcenter.heroku.com/articles/limits) (Heroku docs) + - [Deploying Python applications with Gunicorn](https://devcenter.heroku.com/articles/python-gunicorn) (Heroku docs) + - [Deploying Python and Django apps on Heroku](https://devcenter.heroku.com/articles/deploying-python) (Heroku docs) + - [Other Heroku Django docs](https://devcenter.heroku.com/search?q=django) + +- Digital Ocean + + - [How To Serve Django Applications with uWSGI and Nginx on Ubuntu 16.04](https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-16-04) + - [Other Digital Ocean Django community docs](https://www.digitalocean.com/community/tutorials?q=django) + +{{PreviousMenuNext("Learn/Server-side/Django/Testing", "Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}} + +## In this module + +- [Django introduction](/en-US/docs/Learn/Server-side/Django/Introduction) +- [Setting up a Django development environment](/en-US/docs/Learn/Server-side/Django/development_environment) +- [Django Tutorial: The Local Library website](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django Tutorial Part 2: Creating a skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) +- [Django Tutorial Part 3: Using models](/en-US/docs/Learn/Server-side/Django/Models) +- [Django Tutorial Part 4: Django admin site](/en-US/docs/Learn/Server-side/Django/Admin_site) +- [Django Tutorial Part 5: Creating our home page](/en-US/docs/Learn/Server-side/Django/Home_page) +- [Django Tutorial Part 6: Generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views) +- [Django Tutorial Part 7: Sessions framework](/en-US/docs/Learn/Server-side/Django/Sessions) +- [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/Authentication) +- [Django Tutorial Part 9: Working with forms](/en-US/docs/Learn/Server-side/Django/Forms) +- [Django Tutorial Part 10: Testing a Django web application](/en-US/docs/Learn/Server-side/Django/Testing) +- [Django Tutorial Part 11: Deploying Django to production](/en-US/docs/Learn/Server-side/Django/Deployment) +- [Django web application security](/en-US/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django mini blog](/en-US/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/development_environment/index.html b/files/zh-tw/learn/server-side/django/development_environment/index.html deleted file mode 100644 index 652ead59b1ae0a..00000000000000 --- a/files/zh-tw/learn/server-side/django/development_environment/index.html +++ /dev/null @@ -1,426 +0,0 @@ ---- -title: 架設 Django 開發環境 -slug: Learn/Server-side/Django/development_environment -translation_of: Learn/Server-side/Django/development_environment ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Django/Introduction", "Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django")}}
- -

現在,你知道什麼是Django。那麼我們將向你展示如何在Windows,Linux(Ubuntu)和Mac OSX上設置和測試Django開發環境—無論你常用哪種操作系統,本文應該都能讓你開始開發Django應用程序。

- - - - - - - - - - - - -
先備知識:知道如何打開終端或命令行。了解如何在計算機的操作系統上安裝軟件包。
目標:在你的計算機操作系統上運行Django(2.0)開發環境。
- -

Django 開發環境概覽

- -

Django 使你輕鬆設置自己的電腦,以便開始開發網絡應用。這部分介紹在開發環境可以取得什麼,並概述了部分設置和配置選項。本文的其餘部分,介紹了在Ubuntu,Mac OS X 和 Windows 上,安裝 Django 開發環境的推薦方法,以及如何測試。

- -

什麼是 Django 開發環境?

- -

開發環境是在本地計算機上安裝 Django,你可以在將 Django 部署到生產環境之前,用於開發和測試 Django 應用程序。

- -

Django 本身提供的主要工具,是一組用於創建和使用 Django 項目的 Python 腳本,以及可用於在你的計算機的瀏覽器上,測試本地(即,你的計算機,而不是外部 Web 服務器)Django 網絡應用程序的簡單開發網路服務器 。

- -

還有其他外部工具, 它們構成了開發環境的一部分, 我們將不再贅述。這些包括 文本編輯器 text editor 或編輯代碼的 IDE,以及像 Git 這樣的源代碼控制管理工具,用於安全地管理不同版本的代碼。我們假設你已經安裝了一個文本編輯器。

- -

什麼是Django設置選項?

- -

Django 如何在安裝和配置方面非常靈活。Django可以:

- -
    -
  • 安裝在不同的操作系統上。
  • -
  • 可以一起使用Python 3 和Python 2.
  • -
  • 通過Python包索引(PyPi)安裝,和在許多情況下主機的包管理器應用程序。
  • -
  • 配置為使用幾個數據庫之一,可能需要單獨安裝和配置。
  • -
  • 運行在主系統Python環境中或在單獨的Python虛擬環境中運行。
  • -
- -

每個選項都需要略微不同的配置和設置。以下小節解釋了你的一些選擇。對於本文的其餘部分,我們將介紹Django在少見的操作系統上的設置,考量該模塊的其餘部分。

- -
-

注意: 其他可能的安裝選項在官方Django文檔中介紹。相應文件點擊這裡

-
- -

支持哪些操作系統?

- -

幾乎任何可以運行Python編程語言的機器可以運行Django 網絡應用程序:Windows,Mac OSX,Linux/Unix,Solaris,僅舉幾例。幾乎任何計算機都應該在開發過程中運行Django所需的性能。

- -

在本文中。我們將提供Windows,Mac OS X 和Linux/Unix的說明。

- -

你應該使用什麼版本的Python?

- -

我們建議您使用最新版本 - 在編寫本文時,這是Python 3.7。

- -

如果需要,可以使用Python 3.4或更高版本(將來的版本中將刪除Python 3.4支持)。

- -
-

注意: Python 2.7不能與Django 2.0一起使用(Django 1.11.x系列是最後一個支持Python 2.7的系列)。

-
- -

我們在哪裡下載Django?

- -

有三個地方可以下載Django:

- -
    -
  • Python包含庫(PyPi),使用pip工具.這是獲取最新穩定版本的Django的最佳方式.
  • -
  • 使用計算機軟件包管理器中的版本。與操作系統捆綁在一起的Django的分發提供了一種熟悉的安裝機制。請注意,打包版本可能相當舊,只能安裝到系統Python 環境中(可能不是你想要的)。
  • -
  • 可以從源代碼獲取並安裝的最新版本的Python。這不是推薦給初學者,但是當你準備好開始貢獻給Django本身的時候,它是必需的。
  • -
- -

本文介紹如何從PyPi安裝Django,從獲得最新的穩定版本。

- -

哪個數據庫?

- -

Django支持四個主要數據庫(PostgreSQL,MySQL,Oracle和SQLite),還有一些社區庫,可以為其他流行的SQL和NOSQL數據庫,提供不同級別的支持。我們建議你為生產和開發,選擇相同的數據庫(儘管Django使用其對象關係映射器(ORM)抽像出許多數據庫差異,但是仍然存在可以避免的潛在問題 ).

- -

對於本文(和本模塊的大部分),我們將使用將數據存放在文件中的SQLite數據庫。SQLite旨在用作輕量級數據庫,不能支持高級並發。然而,這確實是唯讀的應用程序的絕佳選擇。

- -
-

注意 :當你使用標準工具(django-admin)啟動你的網站項目時,Django將默認配置為使用SQLite。用來入門,這是一個很好的選擇,因為它不需要額外的配置和設置。

-
- -

安裝到整個本機系統還是Python虛擬環境中?

- -

安裝Python3時,您將獲得一個由所有Python3代碼共享的單一全局環境。雖然您可以在環境中,安裝任何您喜歡的Python軟件包,但您一次只能安裝每個軟件包的一個特定版本。

- -
-

注意: 安裝到全局環境中的Python應用程序可能會相互衝突(即,如果它們依賴於同一程序包的不同版本)。

-
- -

如果您將Django安裝到默認/全局環境中,那麼您將只能在計算機上,定位一個版本的Django。如果您想要創建新網站(使用最新版本的Django)同時仍然維護依賴舊版本的網站,這可能是一個問題。

- -

因此,經驗豐富的Python / Django開發人員,通常在獨立的Python虛擬環境中,運行Python應用程序。這樣可以在一台計算機上,實現多個不同的Django環境。 Django開發團隊本身建議您使用Python虛擬環境!

- -

本模塊假設您已將Django安裝到虛擬環境中,我們將向您展示如何做。

- -

安裝 Python 3

- -

為了使用Django,你需要安裝Python3.同樣你需要Python包管理工具pip3 —用來管理(安裝,更新和刪除)Django和其他Python應用程序使用的Python軟件包/庫。

- -

本書簡要說明如何根據需要檢查什麼版本,並根據需要安裝新版本,適用於Ubuntu Linux 16.04, Mac OS X, and Windows 10。

- -
-

注意 :根據你的平台,您還可以從操作系統自己的軟件包管理器或其他機制安裝Python / pip。對於大多數平台,您可以從https://www.python.org/downloads/下載所需的安裝文件,並使用適當的平台特定方法進行安裝。

-
- -

Ubuntu 18.04

- -

Ubuntu Linux 18.04 LTS默認包含Python 3.6.5。您可以通過在bash終端中運行以下命令來確認:

- -
python3 -V
- Python 3.6.5
- -

然而,在默認情況下,為Python 3(包括Django)安裝軟件包的Python包管理工具不可用。你可以使用以下方式將pip3安裝在bash終端

- -
sudo apt install python3-pip
-
- -

macOS X

- -

Mac OS X "El Capitan" 不包括Python 3.你可以通過在bash終端中運行一下命令來確認:

- -
python3 -V
- -bash: python3: command not found
- -

你可以輕鬆從python.org安裝Python 3(以及pip3工具):

- -
    -
  1. 下載所需的安裝程序: - -
      -
    1. 點擊https://www.python.org/downloads/
    2. -
    3. 選擇Download Python 3.7.0按鈕(確切的版本號可能不同).
    4. -
    -
  2. -
  3. 使用Finder找到文件,然後雙擊包文件。遵循安裝提示。
    - (一般能拖拽就拖拽)
  4. -
- -

你現在可以檢查Pyhon 3來確認成功安裝,如下所示:

- -
python3 -V
- Python 3.7.0
-
- -

你也可以通過列出可用的軟件包來檢查pip3是否安裝:

- -
pip3 list
- -

Windows 10

- -

windows默認不安裝,但你可以從python.org輕鬆安裝它(以及pip3工具):

- -
    -
  1. 下載所需版本: - -
      -
    1. 點擊https://www.python.org/downloads/
    2. -
    3. 選擇Download Python 3.7.0 按鈕(確切的版本號可能不同).
    4. -
    5. 通過雙擊下載的文件並按照提示安裝Python
    6. -
    -
  2. -
- -

你可以通過在命令提示符中輸入以下文本來驗證是否安裝了Python:

- -
py -3 -V
- Python 3.7.0
-
- -

默認情況下,Windows安裝程序包含pip3(python包管理器,你可以列出安裝的軟件包):

- -
pip3 list
-
- -
-

注意: 安裝程序應設置上述命令工作所需的一切。但是,如果您收到無法找到Python 的消息,則可能忘記將其添加到系統路徑中。您可以通過再次運行安裝程序,選擇“修改”"Modify",然後選中第二頁上標有“將Python添加到環境變量”"Add Python to environment variables"的框來執行此操作。

-
- -

在Python虛擬環境中使​​用Django

- -

我們將用於創建虛擬環境的庫是 virtualenvwrapper(Linux和macOS X)和 virtualenvwrapper-win (Windows),後者又使用 virtualenv工具。包裝工具為所有平台上的接口管理創建了一致的界面。

- -

安裝虛擬環境軟體

- -

Ubuntu虛擬環境設置

- -

安裝Python和pip之後,你可以安裝 virtualenvwrapper(包括virtualenv)。可在此處找到官方安裝指南,或按照以下說明操作。

- -

使用pip3安裝該工具:

- -
sudo pip3 install virtualenvwrapper
- -

然後將以下行添加到shell啟動文件的末尾(這是主目錄中的隱藏文件名.bashrc)。這些設置了虛擬環境應該存在的位置,開發項目目錄的位置以及使用此軟件包安裝的腳本的位置 :

- -
export WORKON_HOME=$HOME/.virtualenvs
-export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
-export VIRTUALENVWRAPPER_VIRTUALENV_ARGS=' -p /usr/bin/python3 '
-export PROJECT_HOME=$HOME/Devel
-source /usr/local/bin/virtualenvwrapper.sh
-
- -
-

注意: VIRTUALENVWRAPPER_PYTHONVIRTUALENVWRAPPER_VIRTUALENV_ARGS 變量指向Python3的正常安裝位置,source /usr/local/bin/virtualenvwrapper.sh指向virtualenvwrapper.sh腳本的正常位置。如果virtualenv在測試時不起作用,那麼要檢查的一件事是Python和腳本位於預期的位置(然後適當地更改啟動文件)。

- -

您可以使用which virtualenvwrapper.shwhich python3.的命令找到系統的正確位置。

-
- -

然後在終端中運行以下命令重新加載啟動文件:

- -
source ~/.bashrc
- -

此時您應該看到一堆腳本正在運行,如下所示:

- -
virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/premkproject
-virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postmkproject
-...
-virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/preactivate
-virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postactivate
-virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/get_env_details
-
- -

現在,您可以使用mkvirtualenv命令創建新的虛擬環境。

- -

macOS X 虛擬環境設置

- -

在 macOS X上設置 virtualenvwrapper 與在 Ubuntu上幾乎完全相同(同樣,您可以按照官方安裝指南或下面的說明進行操作。

- -

使用 pip 安裝 virtualenvwrapper(並捆綁 virtualenv),如圖所示。

- -
sudo pip3 install virtualenvwrapper
- -

然後將以下幾行添加到 shell 啟動文件的末尾。

- -
export WORKON_HOME=$HOME/.virtualenvs
-export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
-export PROJECT_HOME=$HOME/Devel
-source /usr/local/bin/virtualenvwrapper.sh
- -
-

注意: VIRTUALENVWRAPPER_PYTHON變量指向Python3的正常安裝位置,source /usr/local/bin/virtualenvwrapper.sh指向virtualenvwrapper.sh腳本的正常位置。如果virtualenv在測試時不起作用,那麼要檢查的一件事,是Python和腳本位於預期的位置(然後適當地更改啟動文件)。

- -

例如,對macOS進行的一次安裝測試,最終在啟動文件中需要以下幾行:

- -
export WORKON_HOME=$HOME/.virtualenvs
-export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
-export PROJECT_HOME=$HOME/Devel
-source /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh
- -

您可以使用which virtualenvwrapper.shwhich python3的命令找到系統的正確位置。

-
- -

這幾行與Ubuntu相同,但啟動文件是主目錄中、名稱不同的隱藏文件.bash_profile

- -
-

注意: 如果在查找程序中找不到要編輯的.bash-profile,也可以使用nano在終端中打開它。

- -

命令看起來像這樣:

- -
cd ~  # Navigate to my home directory
-ls -la #List the content of the directory. YOu should see .bash_profile
-nano .bash_profile # Open the file in the nano text editor, within the terminal
-# Scroll to the end of the file, and copy in the lines above
-# Use Ctrl+X to exit nano, Choose Y to save the file.
-
- -

-
- -

然後通過在終端中,進行以下調用,來重新加載啟動文件:

- -
source ~/.bash_profile
- -

此時,您可能會看到一堆腳本正在運行(與Ubuntu安裝相同的腳本)。您現在應該能夠使用mkvirtualenv命令,創建新的虛擬環境。

- -

Windows 10 虛擬環境設置

- -

安裝virtualenvwrapper-win比設置virtualenvwrapper更簡單,因為您不需要配置工具存放虛擬環境信息的位置(有默認值)。您需要做的就是,在命令提示符中運行以下命令:

- -
pip3 install virtualenvwrapper-win
- -

現在,您可以使用mkvirtualenv命令創建新的虛擬環境

- -

創建虛擬環境

- -

一旦你安裝了virtualenvwrapper或virtualenvwrapper-win,那麼在所有平台上使用虛擬環境都非常相似。

- -

現在,您可以使用mkvirtualenv命令創建新的虛擬環境。當此命令運行時,您將看到正在設置的環境(您看到的是略微特定​​於平台的)。當命令完成時,新的虛擬環境,將處於活動狀態 - 您可以看到這一點,因為提示的開頭,將是括號中環境的名稱(如下所示)。

- -
$ mkvirtualenv my_django_environment
-
-Running virtualenv with interpreter /usr/bin/python3
-...
-virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/t_env7/bin/get_env_details
-(my_django_environment) ubuntu@ubuntu:~$
-
- -

現在,您可以在虛擬環境中,安裝Django,並開始開發。

- -
-

注意: 從本文開始(實際上是本系列教學),請假設任何命令都在Python虛擬環境中運行,就像我們在上面設置的那樣。

-
- -

使用虛擬環境

- -

您應該知道其他一些有用的命令(工具文檔中有更多,但這些是您經常使用的命令):

- -
    -
  • deactivate — 退出當前的Python虛擬環境
  • -
  • workon — 列出可用的虛擬環境
  • -
  • workon name_of_environment — 激活指定的Python虛擬環境
  • -
  • rmvirtualenv name_of_environment — 刪除指定的環境
  • -
- -

安裝 Django

- -

一旦你創建了一個虛擬環境,並調用了workon來輸入它,就可以使用pip3來安裝Django。

- -
pip3 install django
-
- -

您可以通過運行以下命令來測試Django是否安裝(這只是測試Python可以找到Django模塊):

- -
# Linux/macOS X
-python3 -m django --version
- 2.0
-
-# Windows
-py -3 -m django --version
- 2.0
-
- -
-

注意: 如果上面的Windows命令沒有顯示django模塊,請嘗試:

- -
py -m django --version
-在Windows中,Python 3腳本通過在命令前面加上py -3來啟動,儘管這可能會因具體安裝而異。如果遇到任何命令問題,請嘗試省略-3修飾符。在Linux / macOS X中,命令是python3
- -
-

重要提示:本教程的其餘部分,使用Linux命令來調用Python 3(python3)。如果您在Windows上工作,只需將此前綴替換為: py -3

-
- -

測試你的安裝

- -

上面的測試可以工作,但它不是很有趣。一個更有趣的測試是創建一個骨架項目並看到它工作。要做到這一點,先在你的命令提示符/終端導航到你想存儲你Django應用程序的位置。為您的測試站點創建一個文件夾並瀏覽它。

- -
mkdir django_test
-cd django_test
-
- -

然後,您可以使用django-admin工具創建一個名為“ mytestsite ”的新骨架站點,如圖所示。創建網站後,您可以導航到文件夾,您將在其中找到管理項目的主要腳本,名為manage.py

- -
django-admin startproject mytestsite
-cd mytestsite
- -

我們可以使用manage.pyrunserver 命令,從此文件夾內運行開發Web服務器,如圖所示。

- -
$ python3 manage.py runserver
-Performing system checks...
-
-System check identified no issues (0 silenced).
-
-You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
-Run 'python manage.py migrate' to apply them.
-
-December 29, 2017 - 03:03:47
-Django version 2.0, using settings 'mytestsite.settings'
-Starting development server at http://127.0.0.1:8000/
-Quit the server with CONTROL-C.
-
- -
-

注意: 以上命令顯示Linux / macOS X命令。此時您可以忽略有關“14個未應用的遷移”的警告!("14 unapplied migration(s)" )

-
- -

一旦服務器運行,您可以通過導航到本地Web瀏覽器上的以下URL來查看該站點:http://127.0.0.1:8000/。你應該看到一個如下所示的網站:

- -

Django Skeleton App Homepage

- -

總結Summary

- -

您現在已在計算機上啟動並運行Django開發環境。

- -

在測試部分,您還簡要了解了,我們如何使用django-admin startproject,創建一個新的Django網站,並使用開發Web服務器(python3 manage.py runserver)在瀏覽器中運行它。在下一篇文章中,我們將擴展此過程,構建一個簡單、但完整的Web應用程序。

- -

參閱

- - - -

{{PreviousMenuNext("Learn/Server-side/Django/Introduction", "Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django")}}

- -

本教程連結

- - - -

diff --git a/files/zh-tw/learn/server-side/django/development_environment/index.md b/files/zh-tw/learn/server-side/django/development_environment/index.md new file mode 100644 index 00000000000000..f1c02d2a9836f6 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/development_environment/index.md @@ -0,0 +1,409 @@ +--- +title: 架設 Django 開發環境 +slug: Learn/Server-side/Django/development_environment +translation_of: Learn/Server-side/Django/development_environment +--- +{{LearnSidebar}}{{PreviousMenuNext("Learn/Server-side/Django/Introduction", "Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django")}} + +現在,你知道什麼是 Django。那麼我們將向你展示如何在 Windows,Linux(Ubuntu)和 Mac OSX 上設置和測試 Django 開發環境—無論你常用哪種操作系統,本文應該都能讓你開始開發 Django 應用程序。 + + + + + + + + + + + + +
先備知識: + 知道如何打開終端或命令行。了解如何在計算機的操作系統上安裝軟件包。 +
目標:在你的計算機操作系統上運行Django(2.0)開發環境。
+ +## Django 開發環境概覽 + +Django 使你輕鬆設置自己的電腦,以便開始開發網絡應用。這部分介紹在開發環境可以取得什麼,並概述了部分設置和配置選項。本文的其餘部分,介紹了在 Ubuntu,Mac OS X 和 Windows 上,安裝 Django 開發環境的*推薦方法*,以及如何測試。 + +### 什麼是 Django 開發環境? + +開發環境是在本地計算機上安裝 Django,你可以在將 Django 部署到生產環境之前,用於開發和測試 Django 應用程序。 + +Django 本身提供的主要工具,是一組用於創建和使用 Django 項目的 Python 腳本,以及可用於在你的計算機的瀏覽器上,測試本地(即,你的計算機,而不是外部 Web 服務器)Django 網絡應用程序的簡單開發網路服務器 。 + +還有其他外部工具, 它們構成了開發環境的一部分, 我們將不再贅述。這些包括 文本編輯器 [text editor](/en-US/docs/Learn/Common_questions/Available_text_editors) 或編輯代碼的 IDE,以及像 [Git ](https://git-scm.com/)這樣的源代碼控制管理工具,用於安全地管理不同版本的代碼。我們假設你已經安裝了一個文本編輯器。 + +### 什麼是 Django 設置選項? + +Django 如何在安裝和配置方面非常靈活。Django 可以: + +- 安裝在不同的操作系統上。 +- 可以一起使用 Python 3 和 Python 2. +- 通過 Python 包索引(PyPi)安裝,和在許多情況下主機的包管理器應用程序。 +- 配置為使用幾個數據庫之一,可能需要單獨安裝和配置。 +- 運行在主系統 Python 環境中或在單獨的 Python 虛擬環境中運行。 + +每個選項都需要略微不同的配置和設置。以下小節解釋了你的一些選擇。對於本文的其餘部分,我們將介紹 Django 在少見的操作系統上的設置,考量該模塊的其餘部分。 + +> **備註:** 其他可能的安裝選項在官方 Django 文檔中介紹。[相應文件點擊這裡](/zh-CN/docs/learn/Server-side/Django/%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83#furtherreading)。 + +#### 支持哪些操作系統? + +幾乎任何可以運行 Python 編程語言的機器可以運行 Django 網絡應用程序:Windows,Mac OSX,Linux/Unix,Solaris,僅舉幾例。幾乎任何計算機都應該在開發過程中運行 Django 所需的性能。 + +在本文中。我們將提供 Windows,Mac OS X 和 Linux/Unix 的說明。 + +#### 你應該使用什麼版本的 Python? + +我們建議您使用最新版本 - 在編寫本文時,這是 Python 3.7。 + +如果需要,可以使用 Python 3.4 或更高版本(將來的版本中將刪除 Python 3.4 支持)。 + +> **備註:** Python 2.7 不能與 Django 2.0 一起使用(Django 1.11.x 系列是最後一個支持 Python 2.7 的系列)。 + +#### 我們在哪裡下載 Django? + +有三個地方可以下載 Django: + +- Python 包含庫(PyPi),使用**pip**工具.這是獲取最新穩定版本的 Django 的最佳方式. +- 使用計算機軟件包管理器中的版本。與操作系統捆綁在一起的 Django 的分發提供了一種熟悉的安裝機制。請注意,打包版本可能相當舊,只能安裝到系統 Python 環境中(可能不是你想要的)。 +- 可以從源代碼獲取並安裝的最新版本的 Python。這不是推薦給初學者,但是當你準備好開始貢獻給 Django 本身的時候,它是必需的。 + +本文介紹如何從 PyPi 安裝 Django,從獲得最新的穩定版本。 + +#### 哪個數據庫? + +Django 支持四個主要數據庫(PostgreSQL,MySQL,Oracle 和 SQLite),還有一些社區庫,可以為其他流行的 SQL 和 NOSQL 數據庫,提供不同級別的支持。我們建議你為生產和開發,選擇相同的數據庫(儘管 Django 使用其對象關係映射器(ORM)抽像出許多數據庫差異,但是仍然存在可以避免的[潛在問題](https://docs.djangoproject.com/en/1.10/ref/databases/) ). + +對於本文(和本模塊的大部分),我們將使用將數據存放在文件中的 SQLite 數據庫。SQLite 旨在用作輕量級數據庫,不能支持高級並發。然而,這確實是唯讀的應用程序的絕佳選擇。 + +> **備註:** 當你使用標準工具(django-admin)啟動你的網站項目時,Django 將默認配置為使用 SQLite。用來入門,這是一個很好的選擇,因為它不需要額外的配置和設置。 + +#### 安裝到整個本機系統還是 Python 虛擬環境中? + +安裝 Python3 時,您將獲得一個由所有 Python3 代碼共享的單一全局環境。雖然您可以在環境中,安裝任何您喜歡的 Python 軟件包,但您一次只能安裝每個軟件包的一個特定版本。 + +> **備註:** 安裝到全局環境中的 Python 應用程序可能會相互衝突(即,如果它們依賴於同一程序包的不同版本)。 + +如果您將 Django 安裝到默認/全局環境中,那麼您將只能在計算機上,定位一個版本的 Django。如果您想要創建新網站(使用最新版本的 Django)同時仍然維護依賴舊版本的網站,這可能是一個問題。 + +因此,經驗豐富的 Python / Django 開發人員,通常在獨立的 Python 虛擬環境中,運行 Python 應用程序。這樣可以在一台計算機上,實現多個不同的 Django 環境。 Django 開發團隊本身建議您使用 Python 虛擬環境! + +本模塊假設您已將 Django 安裝到虛擬環境中,我們將向您展示如何做。 + +## 安裝 Python 3 + +為了使用 Django,你需要安裝 Python3.同樣你需要[Python 包管理工具](https://pypi.python.org/pypi) — _pip3_ —用來管理(安裝,更新和刪除)Django 和其他 Python 應用程序使用的 Python 軟件包/庫。 + +本書簡要說明如何根據需要檢查什麼版本,並根據需要安裝新版本,適用於**Ubuntu Linux 16.04, Mac OS X, and Windows 10。** + +> **備註:** 根據你的平台,您還可以從操作系統自己的軟件包管理器或其他機制安裝 Python / pip。對於大多數平台,您可以從下載所需的安裝文件,並使用適當的平台特定方法進行安裝。 + +### Ubuntu 18.04 + +Ubuntu Linux 18.04 LTS 默認包含 Python 3.6.5。您可以通過在 bash 終端中運行以下命令來確認: + +```bash +python3 -V + Python 3.6.5 +``` + +然而,在默認情況下,為 Python 3(包括 Django)安裝軟件包的 Python 包管理工具**不可用。你**可以使用以下方式將**pip3**安裝在**bash**終端**:** + +```bash +sudo apt install python3-pip +``` + +### macOS X + +Mac OS X "El Capitan" 不包括 Python 3.你可以通過在 bash 終端中運行一下命令來確認: + +```bash +python3 -V + -bash: python3: command not found +``` + +你可以輕鬆從[python.org](https://www.python.org/)安裝 Python 3(以及 pip3 工具): + +1. 下載所需的安裝程序: + + 1. 點擊 + 2. 選擇**Download Python 3.7.0**按鈕(確切的版本號可能不同). + +2. 使用 Finder 找到文件,然後雙擊包文件。遵循安裝提示。 + (一般能拖拽就拖拽) + +你現在可以檢查 Pyhon 3 來確認成功安裝,如下所示: + +```bash +python3 -V + Python 3.7.0 +``` + +你也可以通過列出可用的軟件包來檢查 pip3 是否安裝: + +```bash +pip3 list +``` + +### Windows 10 + +windows 默認不安裝,但你可以從[python.org](https://www.python.org/)輕鬆安裝它(以及 pip3 工具): + +1. 下載所需版本: + + 1. 點擊 + 2. 選擇**Download Python 3.7.0** 按鈕(確切的版本號可能不同). + 3. 通過雙擊下載的文件並按照提示安裝 Python + +你可以通過在命令提示符中輸入以下文本來驗證是否安裝了 Python: + +```bash +py -3 -V + Python 3.7.0 +``` + +默認情況下,Windows 安裝程序包含 pip3(python 包管理器,你可以列出安裝的軟件包): + +```bash +pip3 list +``` + +> **備註:** 安裝程序應設置上述命令工作所需的一切。但是,如果您收到無法找到 Python 的消息,則可能忘記將其添加到系統路徑中。您可以通過再次運行安裝程序,選擇“修改”"Modify",然後選中第二頁上標有“將 Python 添加到環境變量”"Add Python to environment variables"的框來執行此操作。 + +## 在 Python 虛擬環境中使用 Django + +我們將用於創建虛擬環境的庫是 [virtualenvwrapper](https://virtualenvwrapper.readthedocs.io/en/latest/index.html)(Linux 和 macOS X)和 [virtualenvwrapper-win](https://pypi.python.org/pypi/virtualenvwrapper-win) (Windows),後者又使用 [virtualenv](/en-US/docs/Python/Virtualenv)工具。包裝工具為所有平台上的接口管理創建了一致的界面。 + +### 安裝虛擬環境軟體 + +#### Ubuntu 虛擬環境設置 + +安裝 Python 和 pip 之後,你可以安裝 virtualenvwrapper(包括 virtualenv)。可在[此處](http://virtualenvwrapper.readthedocs.io/en/latest/install.html)找到官方安裝指南,或按照以下說明操作。 + +使用 pip3 安裝該工具: + +```bash +sudo pip3 install virtualenvwrapper +``` + +然後將以下行添加到 shell 啟動文件的末尾(這是主目錄中的隱藏文件名**.bashrc**)。這些設置了虛擬環境應該存在的位置,開發項目目錄的位置以及使用此軟件包安裝的腳本的位置 : + +```bash +export WORKON_HOME=$HOME/.virtualenvs +export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 +export VIRTUALENVWRAPPER_VIRTUALENV_ARGS=' -p /usr/bin/python3 ' +export PROJECT_HOME=$HOME/Devel +source /usr/local/bin/virtualenvwrapper.sh +``` + +> **備註:** `VIRTUALENVWRAPPER_PYTHON` 和 `VIRTUALENVWRAPPER_VIRTUALENV_ARGS `變量指向 Python3 的正常安裝位置,`source /usr/local/bin/virtualenvwrapper.sh`指向`virtualenvwrapper.sh`腳本的正常位置。如果 virtualenv 在測試時不起作用,那麼要檢查的一件事是 Python 和腳本位於預期的位置(然後適當地更改啟動文件)。 +> +> 您可以使用`which virtualenvwrapper.sh` 和 `which python3`.的命令找到系統的正確位置。 + +然後在終端中運行以下命令重新加載啟動文件: + +```bash +source ~/.bashrc +``` + +此時您應該看到一堆腳本正在運行,如下所示: + +```bash +virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/premkproject +virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postmkproject +... +virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/preactivate +virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/postactivate +virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/get_env_details +``` + +現在,您可以使用`mkvirtualenv`命令創建新的虛擬環境。 + +#### macOS X 虛擬環境設置 + +在 macOS X 上設置 virtualenvwrapper 與在 Ubuntu 上幾乎完全相同(同樣,您可以按照[官方安裝指南](http://virtualenvwrapper.readthedocs.io/en/latest/install.html)或下面的說明進行操作。 + +使用 pip 安裝 virtualenvwrapper(並捆綁 virtualenv),如圖所示。 + +```bash +sudo pip3 install virtualenvwrapper +``` + +然後將以下幾行添加到 shell 啟動文件的末尾。 + +```bash +export WORKON_HOME=$HOME/.virtualenvs +export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3 +export PROJECT_HOME=$HOME/Devel +source /usr/local/bin/virtualenvwrapper.sh +``` + +> **備註:** `VIRTUALENVWRAPPER_PYTHON`變量指向 Python3 的正常安裝位置,`source /usr/local/bin/virtualenvwrapper.sh`指向`virtualenvwrapper.sh`腳本的正常位置。如果 virtualenv 在測試時不起作用,那麼要檢查的一件事,是 Python 和腳本位於預期的位置(然後適當地更改啟動文件)。 +> +> 例如,對 macOS 進行的一次安裝測試,最終在啟動文件中需要以下幾行: +> +> ```bash +> export WORKON_HOME=$HOME/.virtualenvs +> export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 +> export PROJECT_HOME=$HOME/Devel +> source /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh +> ``` +> +> 您可以使用`which virtualenvwrapper.sh` 和 `which python3`的命令找到系統的正確位置。 + +這幾行與 Ubuntu 相同,但啟動文件是主目錄中、名稱不同的隱藏文件**.bash_profile**。 + +> **備註:** 如果在查找程序中找不到要編輯的**.bash-profile**,也可以使用 nano 在終端中打開它。 +> +> 命令看起來像這樣: +> +> cd ~ # Navigate to my home directory +> ls -la #List the content of the directory. YOu should see .bash_profile +> nano .bash_profile # Open the file in the nano text editor, within the terminal +> # Scroll to the end of the file, and copy in the lines above +> # Use Ctrl+X to exit nano, Choose Y to save the file. + +然後通過在終端中,進行以下調用,來重新加載啟動文件: + +```bash +source ~/.bash_profile +``` + +此時,您可能會看到一堆腳本正在運行(與 Ubuntu 安裝相同的腳本)。您現在應該能夠使用`mkvirtualenv`命令,創建新的虛擬環境。 + +#### Windows 10 虛擬環境設置 + +安裝[virtualenvwrapper-win](https://pypi.python.org/pypi/virtualenvwrapper-win)比設置 virtualenvwrapper 更簡單,因為您不需要配置工具存放虛擬環境信息的位置(有默認值)。您需要做的就是,在命令提示符中運行以下命令: + + pip3 install virtualenvwrapper-win + +現在,您可以使用`mkvirtualenv`命令創建新的虛擬環境 + +### 創建虛擬環境 + +一旦你安裝了 virtualenvwrapper 或 virtualenvwrapper-win,那麼在所有平台上使用虛擬環境都非常相似。 + +現在,您可以使用`mkvirtualenv`命令創建新的虛擬環境。當此命令運行時,您將看到正在設置的環境(您看到的是略微特定 ​​ 於平台的)。當命令完成時,新的虛擬環境,將處於活動狀態 - 您可以看到這一點,因為提示的開頭,將是括號中環境的名稱(如下所示)。 + + $ mkvirtualenv my_django_environment + + Running virtualenv with interpreter /usr/bin/python3 + ... + virtualenvwrapper.user_scripts creating /home/ubuntu/.virtualenvs/t_env7/bin/get_env_details + (my_django_environment) ubuntu@ubuntu:~$ + +現在,您可以在虛擬環境中,安裝 Django,並開始開發。 + +> **備註:** 從本文開始(實際上是本系列教學),請假設任何命令都在 Python 虛擬環境中運行,就像我們在上面設置的那樣。 + +### 使用虛擬環境 + +您應該知道其他一些有用的命令(工具文檔中有更多,但這些是您經常使用的命令): + +- `deactivate` — 退出當前的 Python 虛擬環境 +- `workon` — 列出可用的虛擬環境 +- `workon name_of_environment` — 激活指定的 Python 虛擬環境 +- `rmvirtualenv name_of_environment` — 刪除指定的環境 + +## 安裝 Django + +一旦你創建了一個虛擬環境,並調用了`workon`來輸入它,就可以使用 pip3 來安裝 Django。 + +```bash +pip3 install django +``` + +您可以通過運行以下命令來測試 Django 是否安裝(這只是測試 Python 可以找到 Django 模塊): + +```bash +# Linux/macOS X +python3 -m django --version + 2.0 + +# Windows +py -3 -m django --version + 2.0 +``` + +> **備註:** 如果上面的 Windows 命令沒有顯示 django 模塊,請嘗試: +> +> ```bash +> py -m django --version +> ``` +> +> 在 Windows 中,Python 3 腳本通過在命令前面加上`py -3`來啟動,儘管這可能會因具體安裝而異。如果遇到任何命令問題,請嘗試省略`-3`修飾符。在 Linux / macOS X 中,命令是`python3`。 + +> **警告:** 本教程的其餘部分,使用 Linux 命令來調用 Python 3(python3)。如果您在 Windows 上工作,只需將此前綴替換為:` py -3` + +## 測試你的安裝 + +上面的測試可以工作,但它不是很有趣。一個更有趣的測試是創建一個骨架項目並看到它工作。要做到這一點,先在你的命令提示符/終端導航到你想存儲你**Django**應用程序的位置。為您的測試站點創建一個文件夾並瀏覽它。 + +```bash +mkdir django_test +cd django_test +``` + +然後,您可以使用**django-admin**工具創建一個名為“ **mytestsite** ”的新骨架站點,如圖所示。創建網站後,您可以導航到文件夾,您將在其中找到管理項目的主要腳本,名為**manage.py**。 + +```bash +django-admin startproject mytestsite +cd mytestsite +``` + +我們可以使用**manage.py**和 `runserver `命令,從此文件夾內運行開發 Web 服務器,如圖所示。 + +```bash +$ python3 manage.py runserver +Performing system checks... + +System check identified no issues (0 silenced). + +You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. +Run 'python manage.py migrate' to apply them. + +December 29, 2017 - 03:03:47 +Django version 2.0, using settings 'mytestsite.settings' +Starting development server at http://127.0.0.1:8000/ +Quit the server with CONTROL-C. +``` + +> **備註:** 以上命令顯示 Linux / macOS X 命令。此時您可以忽略有關“14 個未應用的遷移”的警告!("14 unapplied migration(s)" ) + +一旦服務器運行,您可以通過導航到本地 Web 瀏覽器上的以下 URL 來查看該站點:`http://127.0.0.1:8000/`。你應該看到一個如下所示的網站: + +![Django Skeleton App Homepage](django_skeleton_app_homepage_django_4_0.png) + +## 總結 Summary + +您現在已在計算機上啟動並運行 Django 開發環境。 + +在測試部分,您還簡要了解了,我們如何使用`django-admin startproject`,創建一個新的 Django 網站,並使用開發 Web 服務器(`python3 manage.py runserver`)在瀏覽器中運行它。在下一篇文章中,我們將擴展此過程,構建一個簡單、但完整的 Web 應用程序。 + +## 參閱 + +- [Quick Install Guide](https://docs.djangoproject.com/en/2.0/intro/install/) (Django docs) +- [How to install Django — Complete guide](https://docs.djangoproject.com/en/2.0/topics/install/) (Django docs) - includes information on how to remove Django +- [How to install Django on Windows](https://docs.djangoproject.com/en/2.0/howto/windows/) (Django docs) + +{{PreviousMenuNext("Learn/Server-side/Django/Introduction", "Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django")}} + +## 本教程連結 + +- [Django introduction](/en-US/docs/Learn/Server-side/Django/Introduction) +- [Setting up a Django development environment](/en-US/docs/Learn/Server-side/Django/development_environment) +- [Django Tutorial: The Local Library website](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django Tutorial Part 2: Creating a skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) +- [Django Tutorial Part 3: Using models](/en-US/docs/Learn/Server-side/Django/Models) +- [Django Tutorial Part 4: Django admin site](/en-US/docs/Learn/Server-side/Django/Admin_site) +- [Django Tutorial Part 5: Creating our home page](/en-US/docs/Learn/Server-side/Django/Home_page) +- [Django Tutorial Part 6: Generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views) +- [Django Tutorial Part 7: Sessions framework](/en-US/docs/Learn/Server-side/Django/Sessions) +- [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/Authentication) +- [Django Tutorial Part 9: Working with forms](/en-US/docs/Learn/Server-side/Django/Forms) +- [Django Tutorial Part 10: Testing a Django web application](/en-US/docs/Learn/Server-side/Django/Testing) +- [Django Tutorial Part 11: Deploying Django to production](/en-US/docs/Learn/Server-side/Django/Deployment) +- [Django web application security](/en-US/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django mini blog](/en-US/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/django_assessment_blog/index.html b/files/zh-tw/learn/server-side/django/django_assessment_blog/index.html deleted file mode 100644 index 742761775ed05c..00000000000000 --- a/files/zh-tw/learn/server-side/django/django_assessment_blog/index.html +++ /dev/null @@ -1,316 +0,0 @@ ---- -title: 'Assessment: DIY Django mini blog' -slug: Learn/Server-side/Django/django_assessment_blog -tags: - - django - - 初學者 - - 部落格 -translation_of: Learn/Server-side/Django/django_assessment_blog ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}}
- -

在這個評估中,您將使用您在 Django Web Framework (Python) 模組中獲得的知識,來創建一個非常基本的部落格。

- - - - - - - - - - - - -
-

前提:

-
在開始時做這章節的任務之前,你應該已經看完這個模組的所有文章了。
目標: -

測試Django基礎的綜合應用,包含URL設定、模型、視圖、表單和模板。

-
- -

專案簡介

- -

需要顯示的頁面與對應的URLs和需求提列於下表:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
頁面URL需求
首頁//blog/關於此站的說明。
所有部落格文章的清單/blog/blogs/ -

所有部落格文章的清單。

- -
    -
  • 所有使用者都能從側邊選單進入此頁。
  • -
  • 清單按發布日期排序(新至舊)。
  • -
  • 清單依照每頁5筆文章分頁。
  • -
  • 清單內的每一筆項目顯示文章標題、發布日期與作者的名字。
  • -
  • 文章標題連結至該至文章的詳細頁面。
  • -
  • 作者的名字連結至該作者的詳細頁面。
  • -
-
部落格作者(blogger) 詳細頁面/blog/blogger/<author-id> -

特定作者(由id指定)的資訊與他所發布的部落格文章。

- -
    -
  • 所有使用者都能從作者連結進入此頁(例如文章內的作者連結)。
  • -
  • 包含一些關於作者本身的資訊。
  • -
  • 文章清單按發布日期排序(新至舊)。
  • -
  • 不用分頁。
  • -
  • 文章清單只顯示文章標題與發佈日期。
  • -
  • 文章標題連結至文章詳細頁面。
  • -
-
部落格文章詳細頁面/blog/<blog-id> -

部落格文章詳細內容。

- -
    -
  • 任何使用者都能從部落格文章的清單進入此頁。
  • -
  • 包含文章標題、作者、發布日期與內容。
  • -
  • 文章的回覆必須呈現於底部。
  • -
  • 文章的回覆必須按回覆時間排序(舊至新)。
  • -
  • 已登入的使用者能看見新增回覆的連結。
  • -
  • 文章與回覆需以純文字的方式顯示。不需要支援任何markup(例如連結、圖片、粗體/斜體等)。
  • -
-
部落格作者清單/blog/bloggers/ -

系統內的部落格作者清單。

- -
    -
  • 任何使用者都可以從側邊選單進入此頁。
  • -
  • 作者名字連結至該作者的詳細頁面。
  • -
-
回覆表單頁/blog/<blog-id>/create -

新增回覆於特定文章。

- -
    -
  • 只有登入的使用者可以由文章詳細頁面底部連結進入此頁。
  • -
  • 提供能輸入回覆的表單(發布日期和文章標題不可被編輯)。
  • -
  • 回覆被發表之後,頁面會轉址回該文章詳細頁。
  • -
  • 使用者無法修改或是刪除他發表的回覆。
  • -
  • 未登入的使用者會先被導至登入頁,登入之後才能發表回覆。一旦登入之後,他們便會被導至他們想發表回覆的文章頁。
  • -
  • 回覆表單頁必須包含該文章的標題與連結。
  • -
-
使用者身分認證頁/accounts/<standard urls> -

標準的Django身分驗證頁面,用來登入、登出及修改密碼。

- -
    -
  • 使用者能從側欄連結進入登入/登出頁面。
  • -
-
管理者網頁/admin/<standard urls> -

管理者網頁必須能新增/編輯/刪除部落格文章、作者及回覆。

- -
    -
  • 管理者網頁的每筆文章記錄必須一併於其底下陳列出相關的回覆。
  • -
  • 管理者網頁的每一筆回覆都要以75字的回覆內容作為顯示名稱。
  • -
  • 其餘的紀錄使用基本的註冊即可。
  • -
-
- -

另外您應該要寫一些基本的測試來驗證:

- -
    -
  • 所有的模型欄位都有正確的標示和長度。
  • -
  • 所有的模型都有期望的物件名稱(例如 __str__() 回傳期望的值)。
  • -
  • 模型有期望的URL給每篇文章與回覆。(例如get_absolute_url() 回傳期望的URL)。
  • -
  • BlogListView (所有文章的頁面) 可以從期望的位址進入(例如/blog/blogs)。
  • -
  • BlogListView (所有文章的頁面) 可以從期望的位址名稱進入(例如'blogs')。
  • -
  • BlogListView (所有文章的頁面) 使用期望的模板(例如預設值)。
  • -
  • BlogListView 以每頁5筆項目分頁(至少第一頁是如此)。
  • -
- -
-

Note: 當然你也可以跑很多其他的測試。但是我們會希望您至少實作以上列出的測試項目。

-
- -

下一區塊顯示符合以上需求的網頁截圖

- -

截圖

- -

The following screenshot provide an example of what the finished program should output.

- -

列出所有的部落格文章

- -

這個頁面會列出所有部落格內的文章(可以從側邊選單的“所有文章”連結進入)。
- 幾項提醒:

- -
    -
  • 側邊選單也要列出目前登入的使用者。
  • -
  • 每篇文章與部落客都能透過連結的方式進入。
  • -
  • 必須要有分頁(每頁5筆資料)。
  • -
  • 文章排列順序由最新至最舊。
  • -
- -

List of all blogs

- -

列出所有部落客(文章作者)

- -

可以由側邊選單的“所有部落客”進入此頁面,並於頁面上提供連結至每一位部落客。
- 從截圖可以發現到,並沒有任何一位使用者登入。

- -

List of all bloggers

- -

部落格詳細頁

- -

顯示某篇特定部落格文章的詳細內容。

- -

Blog detail with add comment link

- -

請注意每個評論都有日期與時間,並且由最後至最新排列(與部落格文章相反)。
- 我們可以看見最底下有個連結連到新增評論的表單。當使用者沒有登入時,我們改以要求登入的連結代替。

- -

Comment link when not logged in

- -

新增評論表單

- -

這張表單用來新增評論,且使用者必須是登入狀態。當表單送出成功之後,我們必須回到相對應的部落格文章內容頁。

- -

Add comment form

- -

作者資料

- -

這頁顯示部落客的介紹資料以及列出他們所發表的部落格文章。

- -

Blogger detail page

- -

一步一腳印Steps to complete

- -

以下說明實作的步驟。

- -
    -
  1. 建立一個此網站的專案及app骨架(可以參考Django 教學2 : 建立一個網站骨架)。你也許會用'diyblog'作為專案名稱,‘blog'作為app的名稱。
  2. -
  3. 建立部落格文章、評論與其他任何所需物件的模型。當你在思考怎麼設計的時候,請記得: -
      -
    • 每一個評論都只屬於一篇部落格文章,但每一個部落格文章可以有很多筆評論。
    • -
    • 部落格文章必須要依照發布時間排序(新至舊),評論要依照發布排序(舊至新)。
    • -
    • 不是每位使用者都是部落客,但是每一位使用者都可以留下評論。
    • -
    • 部落客必須有介紹資訊。
    • -
    -
  4. -
  5. 跑migrations以及創建一個新的超級使用者(superuser)。
  6. -
  7. 透過admin網站新稱一些部落格文章和評論。
  8. -
  9. 幫部落格文章列表頁與部落客列表頁建立視圖、模板及設定URL。
  10. -
  11. 幫部落格文章詳細頁與部落客詳細頁建立視圖、模板及設定URL。
  12. -
  13. 建立一個頁面包含可以新增評論的表單(記得只有已登入的使用者可以進入此頁!)
  14. -
- -

提示與小技巧

- -

This project is very similar to the LocalLibrary tutorial. You will be able to set up the skeleton, user login/logout behaviour, support for static files, views, URLs, forms, base templates and admin site configuration using almost all the same approaches.

- -

Some general hints:

- -
    -
  1. The index page can be implemented as a basic function view and template (just like for the locallibrary).
  2. -
  3. The list view for blog posts and bloggers, and the detail view for blog posts can be created using the generic list and detail views.
  4. -
  5. The list of blog posts for a particular author can be created by using a generic list Blog list view and filtering for blog object that match the specified author. -
      -
    • You will have to implement get_queryset(self) to do the filtering (much like in our library class LoanedBooksAllListView) and get the author information from the URL.
    • -
    • You will also need to pass the name of the author to the page in the context. To do this in a class-based view you need to implement get_context_data() (discussed below).
    • -
    -
  6. -
  7. The add comment form can be created using a function-based view (and associated model and form) or using a generic CreateView. If you use a CreateView (recommended) then: -
      -
    • You will also need to pass the name of the blog post to the comment page in the context (implement get_context_data() as discussed below).
    • -
    • The form should only display the comment "description" for user entry (date and associated blog post should not be editable). Since they won't be in the form itself, your code will need to set the comment's author in the form_valid() function so it can be saved into the model (as described here — Django docs). In that same function we set the associated blog. A possible implementation is shown below (pk is a blog id passed in from the URL/URL configuration). -
          def form_valid(self, form):
      -        """
      -        Add author and associated blog to form data before setting it as valid (so it is saved to model)
      -        """
      -        #Add logged-in user as author of comment
      -        form.instance.author = self.request.user
      -        #Associate comment with blog based on passed id
      -        form.instance.blog=get_object_or_404(Blog, pk = self.kwargs['pk'])
      -        # Call super-class form validation behaviour
      -        return super(BlogCommentCreate, self).form_valid(form)
      -
      -
    • -
    • You will need to provide a success URL to redirect to after the form validates; this should be the original blog. To do this you will need to override get_success_url() and "reverse" the URL for the original blog. You can get the required blog ID using the self.kwargs attribute, as shown in the form_valid() method above.
    • -
    -
  8. -
- -

We briefly talked about passing a context to the template in a class-based view in the Django Tutorial Part 6: Generic list and detail views topic. To do this you need to override get_context_data() (first getting the existing context, updating it with whatever additional variables you want to pass to the template, and then returning the updated context). For example, the code fragment below shows how you can add a blogger object to the context based on their BlogAuthor id.

- -
class SomeView(generic.ListView):
-    ...
-
-    def get_context_data(self, **kwargs):
-        # Call the base implementation first to get a context
-        context = super(SomeView, self).get_context_data(**kwargs)
-        # Get the blogger object from the "pk" URL parameter and add it to the context
-        context['blogger'] = get_object_or_404(BlogAuthor, pk = self.kwargs['pk'])
-        return context
-
- -

Assessment

- -

The assessment for this task is available on Github here. This assessment is primarily based on how well your application meets the requirements we listed above, though there are some parts of the assessment that check your code uses appropriate models, and that you have written at least some test code. When you're done, you can check out our the finished example which reflects a "full marks" project.

- -

Once you've completed this module you've also finished all the MDN content for learning basic Django server-side website programming! We hope you enjoyed this module and feel you have a good grasp of the basics!

- -

{{PreviousMenu("Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}}

- -

In this module

- - diff --git a/files/zh-tw/learn/server-side/django/django_assessment_blog/index.md b/files/zh-tw/learn/server-side/django/django_assessment_blog/index.md new file mode 100644 index 00000000000000..11ec454cae0eb4 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/django_assessment_blog/index.md @@ -0,0 +1,304 @@ +--- +title: 'Assessment: DIY Django mini blog' +slug: Learn/Server-side/Django/django_assessment_blog +tags: + - django + - 初學者 + - 部落格 +translation_of: Learn/Server-side/Django/django_assessment_blog +--- +{{LearnSidebar}}{{PreviousMenu("Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}} + +在這個評估中,您將使用您在 [Django Web Framework (Python)](/en-US/docs/Learn/Server-side/Django) 模組中獲得的知識,來創建一個非常基本的部落格。 + + + + + + + + + + + + +

前提:

在開始時做這章節的任務之前,你應該已經看完這個模組的所有文章了。
目標: +

測試Django基礎的綜合應用,包含URL設定、模型、視圖、表單和模板。

+
+ +## 專案簡介 + +需要顯示的頁面與對應的 URLs 和需求提列於下表: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
頁面URL需求
首頁//blog/關於此站的說明。
所有部落格文章的清單/blog/blogs/ +

所有部落格文章的清單。

+
    +
  • 所有使用者都能從側邊選單進入此頁。
  • +
  • 清單按發布日期排序(新至舊)。
  • +
  • 清單依照每頁5筆文章分頁。
  • +
  • 清單內的每一筆項目顯示文章標題、發布日期與作者的名字。
  • +
  • 文章標題連結至該至文章的詳細頁面。
  • +
  • 作者的名字連結至該作者的詳細頁面。
  • +
+
部落格作者(blogger) 詳細頁面 + /blog/blogger/<author-id> + +

特定作者(由id指定)的資訊與他所發布的部落格文章。

+
    +
  • 所有使用者都能從作者連結進入此頁(例如文章內的作者連結)。
  • +
  • 包含一些關於作者本身的資訊。
  • +
  • 文章清單按發布日期排序(新至舊)。
  • +
  • 不用分頁。
  • +
  • 文章清單只顯示文章標題與發佈日期。
  • +
  • 文章標題連結至文章詳細頁面。
  • +
+
部落格文章詳細頁面 + /blog/<blog-id> + +

部落格文章詳細內容。

+
    +
  • 任何使用者都能從部落格文章的清單進入此頁。
  • +
  • 包含文章標題、作者、發布日期與內容。
  • +
  • 文章的回覆必須呈現於底部。
  • +
  • 文章的回覆必須按回覆時間排序(舊至新)。
  • +
  • 已登入的使用者能看見新增回覆的連結。
  • +
  • + 文章與回覆需以純文字的方式顯示。不需要支援任何markup(例如連結、圖片、粗體/斜體等)。 +
  • +
+
部落格作者清單/blog/bloggers/ +

系統內的部落格作者清單。

+
    +
  • 任何使用者都可以從側邊選單進入此頁。
  • +
  • 作者名字連結至該作者的詳細頁面。
  • +
+
回覆表單頁/blog/<blog-id>/create +

新增回覆於特定文章。

+
    +
  • 只有登入的使用者可以由文章詳細頁面底部連結進入此頁。
  • +
  • 提供能輸入回覆的表單(發布日期和文章標題不可被編輯)。
  • +
  • 回覆被發表之後,頁面會轉址回該文章詳細頁。
  • +
  • 使用者無法修改或是刪除他發表的回覆。
  • +
  • + 未登入的使用者會先被導至登入頁,登入之後才能發表回覆。一旦登入之後,他們便會被導至他們想發表回覆的文章頁。 +
  • +
  • 回覆表單頁必須包含該文章的標題與連結。
  • +
+
使用者身分認證頁 + /accounts/<standard urls> + +

標準的Django身分驗證頁面,用來登入、登出及修改密碼。

+
    +
  • 使用者能從側欄連結進入登入/登出頁面。
  • +
+
管理者網頁 + /admin/<standard urls> + +

管理者網頁必須能新增/編輯/刪除部落格文章、作者及回覆。

+
    +
  • 管理者網頁的每筆文章記錄必須一併於其底下陳列出相關的回覆。
  • +
  • 管理者網頁的每一筆回覆都要以75字的回覆內容作為顯示名稱。
  • +
  • 其餘的紀錄使用基本的註冊即可。
  • +
+
+ +另外您應該要寫一些基本的測試來驗證: + +- 所有的模型欄位都有正確的標示和長度。 +- 所有的模型都有期望的物件名稱(例如` __str__()` 回傳期望的值)。 +- 模型有期望的 URL 給每篇文章與回覆。(例如`get_absolute_url()` 回傳期望的 URL)。 +- BlogListView (所有文章的頁面) 可以從期望的位址進入(例如/blog/blogs)。 +- BlogListView (所有文章的頁面) 可以從期望的位址名稱進入(例如'blogs')。 +- BlogListView (所有文章的頁面) 使用期望的模板(例如預設值)。 +- BlogListView 以每頁 5 筆項目分頁(至少第一頁是如此)。 + +> **備註:** 當然你也可以跑很多其他的測試。但是我們會希望您至少實作以上列出的測試項目。 + +下一區塊顯示符合以上需求的網頁[截圖](#Screenshots)。 + +## 截圖 + +The following screenshot provide an example of what the finished program should output. + +### 列出所有的部落格文章 + +這個頁面會列出所有部落格內的文章(可以從側邊選單的“所有文章”連結進入)。 +幾項提醒: + +- 側邊選單也要列出目前登入的使用者。 +- 每篇文章與部落客都能透過連結的方式進入。 +- 必須要有分頁(每頁 5 筆資料)。 +- 文章排列順序由最新至最舊。 + +![List of all blogs](diyblog_allblogs.png) + +### 列出所有部落客(文章作者) + +可以由側邊選單的“所有部落客”進入此頁面,並於頁面上提供連結至每一位部落客。 +從截圖可以發現到,並沒有任何一位使用者登入。 + +![List of all bloggers](diyblog_blog_allbloggers.png) + +### 部落格詳細頁 + +顯示某篇特定部落格文章的詳細內容。 + +![Blog detail with add comment link](diyblog_blog_detail_add_comment.png) + +請注意每個評論都有日期與時間,並且由最後至最新排列(與部落格文章相反)。 +我們可以看見最底下有個連結連到新增評論的表單。當使用者沒有登入時,我們改以要求登入的連結代替。 + +![Comment link when not logged in](diyblog_blog_detail_not_logged_in.png) + +### 新增評論表單 + +這張表單用來新增評論,且使用者必須是登入狀態。當表單送出成功之後,我們必須回到相對應的部落格文章內容頁。 + +![Add comment form](diyblog_comment_form.png) + +### 作者資料 + +這頁顯示部落客的介紹資料以及列出他們所發表的部落格文章。 + +![Blogger detail page](diyblog_blogger_detail.png) + +## 一步一腳印 Steps to complete + +以下說明實作的步驟。 + +1. 建立一個此網站的專案及 app 骨架(可以參考[Django 教學 2 : 建立一個網站骨架](/en-US/docs/Learn/Server-side/Django/skeleton_website))。你也許會用'diyblog'作為專案名稱,‘blog'作為 app 的名稱。 +2. 建立部落格文章、評論與其他任何所需物件的模型。當你在思考怎麼設計的時候,請記得: + + - 每一個評論都只屬於一篇部落格文章,但每一個部落格文章可以有很多筆評論。 + - 部落格文章必須要依照發布時間排序(新至舊),評論要依照發布排序(舊至新)。 + - 不是每位使用者都是部落客,但是每一位使用者都可以留下評論。 + - 部落客必須有介紹資訊。 + +3. 跑 migrations 以及創建一個新的超級使用者(superuser)。 +4. 透過 admin 網站新稱一些部落格文章和評論。 +5. 幫部落格文章列表頁與部落客列表頁建立視圖、模板及設定 URL。 +6. 幫部落格文章詳細頁與部落客詳細頁建立視圖、模板及設定 URL。 +7. 建立一個頁面包含可以新增評論的表單(記得只有已登入的使用者可以進入此頁!) + +## 提示與小技巧 + +This project is very similar to the [LocalLibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) tutorial. You will be able to set up the skeleton, user login/logout behaviour, support for static files, views, URLs, forms, base templates and admin site configuration using almost all the same approaches. + +Some general hints: + +1. The index page can be implemented as a basic function view and template (just like for the locallibrary). +2. The list view for blog posts and bloggers, and the detail view for blog posts can be created using the [generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views). +3. The list of blog posts for a particular author can be created by using a generic list Blog list view and filtering for blog object that match the specified author. + + - You will have to implement `get_queryset(self)` to do the filtering (much like in our library class `LoanedBooksAllListView`) and get the author information from the URL. + - You will also need to pass the name of the author to the page in the context. To do this in a class-based view you need to implement `get_context_data()` (discussed below). + +4. The _add comment_ form can be created using a function-based view (and associated model and form) or using a generic `CreateView`. If you use a `CreateView` (recommended) then: + + - You will also need to pass the name of the blog post to the comment page in the context (implement `get_context_data()` as discussed below). + - The form should only display the comment "description" for user entry (date and associated blog post should not be editable). Since they won't be in the form itself, your code will need to set the comment's author in the` form_valid()` function so it can be saved into the model ([as described here](https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-editing/#models-and-request-user) — Django docs). In that same function we set the associated blog. A possible implementation is shown below (`pk` is a blog id passed in from the URL/URL configuration). + + ```python + def form_valid(self, form): + """ + Add author and associated blog to form data before setting it as valid (so it is saved to model) + """ + #Add logged-in user as author of comment + form.instance.author = self.request.user + #Associate comment with blog based on passed id + form.instance.blog=get_object_or_404(Blog, pk = self.kwargs['pk']) + # Call super-class form validation behaviour + return super(BlogCommentCreate, self).form_valid(form) + ``` + + - You will need to provide a success URL to redirect to after the form validates; this should be the original blog. To do this you will need to override `get_success_url()` and "reverse" the URL for the original blog. You can get the required blog ID using the `self.kwargs` attribute, as shown in the `form_valid()` method above. + +We briefly talked about passing a context to the template in a class-based view in the [Django Tutorial Part 6: Generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views#Overriding_methods_in_class-based_views) topic. To do this you need to override `get_context_data()` (first getting the existing context, updating it with whatever additional variables you want to pass to the template, and then returning the updated context). For example, the code fragment below shows how you can add a blogger object to the context based on their `BlogAuthor` id. + +```python +class SomeView(generic.ListView): + ... + + def get_context_data(self, **kwargs): + # Call the base implementation first to get a context + context = super(SomeView, self).get_context_data(**kwargs) + # Get the blogger object from the "pk" URL parameter and add it to the context + context['blogger'] = get_object_or_404(BlogAuthor, pk = self.kwargs['pk']) + return context +``` + +## Assessment + +The assessment for this task is [available on Github here](https://github.com/mdn/django-diy-blog/blob/master/MarkingGuide.md). This assessment is primarily based on how well your application meets the requirements we listed above, though there are some parts of the assessment that check your code uses appropriate models, and that you have written at least some test code. When you're done, you can check out our [the finished example](https://github.com/mdn/django-diy-blog) which reflects a "full marks" project. + +Once you've completed this module you've also finished all the MDN content for learning basic Django server-side website programming! We hope you enjoyed this module and feel you have a good grasp of the basics! + +{{PreviousMenu("Learn/Server-side/Django/web_application_security", "Learn/Server-side/Django")}} + +## In this module + +- [Django introduction](/en-US/docs/Learn/Server-side/Django/Introduction) +- [Setting up a Django development environment](/en-US/docs/Learn/Server-side/Django/development_environment) +- [Django Tutorial: The Local Library website](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django Tutorial Part 2: Creating a skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) +- [Django Tutorial Part 3: Using models](/en-US/docs/Learn/Server-side/Django/Models) +- [Django Tutorial Part 4: Django admin site](/en-US/docs/Learn/Server-side/Django/Admin_site) +- [Django Tutorial Part 5: Creating our home page](/en-US/docs/Learn/Server-side/Django/Home_page) +- [Django Tutorial Part 6: Generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views) +- [Django Tutorial Part 7: Sessions framework](/en-US/docs/Learn/Server-side/Django/Sessions) +- [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/Authentication) +- [Django Tutorial Part 9: Working with forms](/en-US/docs/Learn/Server-side/Django/Forms) +- [Django Tutorial Part 10: Testing a Django web application](/en-US/docs/Learn/Server-side/Django/Testing) +- [Django Tutorial Part 11: Deploying Django to production](/en-US/docs/Learn/Server-side/Django/Deployment) +- [Django web application security](/en-US/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django mini blog](/en-US/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/forms/index.html b/files/zh-tw/learn/server-side/django/forms/index.html deleted file mode 100644 index 63b3a27f5a1062..00000000000000 --- a/files/zh-tw/learn/server-side/django/forms/index.html +++ /dev/null @@ -1,661 +0,0 @@ ---- -title: 'Django Tutorial Part 9: Working with forms' -slug: Learn/Server-side/Django/Forms -translation_of: Learn/Server-side/Django/Forms ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Django/authentication_and_sessions", "Learn/Server-side/Django/Testing", "Learn/Server-side/Django")}}
- -

在本教程中,我們將向您展示,如何在 Django 中使用 HTML 表單,特別是編寫表單以創建,更新和刪除模型實例的最簡單方法。作為本演示的一部分,我們將擴展 LocalLibrary 網站,以便圖書館員,可以使用我們自己的表單(而不是使用管理員應用程序)更新圖書,創建,更新和刪除作者。

- - - - - - - - - - - - -
前提:完成先前所有的教程, 包含 Django Tutorial Part 8: User authentication and permissions.
目的:了解如何製作表單來向用戶取得資訊並更新資料庫。了解通用類別表單編輯視圖 ( generic class-based form editing views ) 能夠大幅簡化用於單一模型的表單製作。
- -

概述

- -

HTML表單是網頁上的一組一個或多個字段/小組件,可用於從用戶收集信息以提交到服務器。 表單是一種用於收集用戶輸入的靈活機制,因為有合適的小部件可以輸入許多不同類型的數據,包括文本框,複選框,單選按鈕,日期選擇器等。表單也是與服務器共享數據的相對安全的方式, 因為它們允許我們在具有跨站點請求偽造保護的POST 請求中發送數據。

- -

儘管到目前為止,本教程中尚未創建任何表單,但我們已經在Django Admin網站中遇到過這些表單-例如,下面的屏幕截圖顯示了一種用於編輯我們的Book 模型的表單,該表單由許多選擇列表和 文字編輯器。

- -

Admin Site - Book Add

- -

使用表單可能會很複雜!開發人員需要為表單編寫HTML,在服務器上(也可能在瀏覽器中)驗證並正確清理輸入的數據,使用錯誤消息重新發布表單以通知用戶任何無效字段,並在成功提交數據後處理數據,最後以某種方式回應用戶以表示成功。 Django表單通過提供一個框架使您能夠以編程方式定義表單及其字段,然後使用這些對像生成表單HTML代碼並處理許多驗證和用戶交互,從而完成了所有這些步驟中的大量工作。

- -

在本教程中,我們將向您展示創建和使用表單的幾種方法,尤其是通用編輯表單視圖如何顯著減少創建表單來操縱表單所需的工作量。楷模。在此過程中,我們將擴展本地圖書館應用程序,方法是添加一個允許圖書館員續訂圖書的表格,並創建頁面以創建,編輯和刪除圖書和作者(複製上面顯示的表格的基本版本以編輯圖書) )。

- -

HTML 表單

- -

首先簡要介紹一下 HTML Forms。 考慮一個簡單的 HTML 表單,其中有一個用於輸入某些“團隊”名稱的文本字段及其相關標籤:

- -

Simple name field example in HTML form

- -

表單在HTML中定義為 <form>...</form> 標記內元素的集合,其中至少包含type="submit".的input元素。

- -
<form action="/team_name_url/" method="post">
-    <label for="team_name">Enter name: </label>
-    <input id="team_name" type="text" name="name_field" value="Default name for team.">
-    <input type="submit" value="OK">
-</form>
- -

雖然這裡只有一個用於輸入團隊名稱的文本字段,但是表單可以具有任意數量的其他輸入元素及其關聯的標籤。字段的type 屬性定義將顯示哪種小部件。字段的 nameid 用於標識JavaScript / CSS / HTML中的字段,而 value定義該字段在首次顯示時的初始值。匹配的團隊標籤是使用label 標籤指定的(請參見上面的“輸入名稱”),其中的 for 字段包含相關inputid 值。

- -

submit 輸入將顯示為一個按鈕(默認情況下),用戶可以按下該按鈕以將表單中所有其他輸入元素中的數據上載到服務器(在這種情況下,僅是team_name)。表單屬性定義用於發送數據的HTTPmethod 以及服務器上數據的目的地(action):
-

- -
    -
  • action: 提交表單時,將數據發送到該資源/ URL進行處理。如果未設置(或設置為空字符串),則表單將被提交回當前頁面URL。
  • -
  • method: 用於發送數據的HTTP方法:post或get。 -
      -
    • 如果數據將導致服務器數據庫的更改,則應始終使用POST 方法,因為這樣可以使它更能抵抗跨站點的偽造請求攻擊。
    • -
    • GET 方法應僅用於不更改用戶數據的表單(例如搜索表單)。建議您在希望添加書籤或共享URL時使用。
    • -
    -
  • -
- -

服務器的角色是首先呈現初始表單狀態-包含空白字段,或預填充初始值。用戶按下“提交”按鈕後,服務器將從Web瀏覽器接收帶有值的表單數據,並且必須驗證信息。如果表單包含無效數據,則服務器應再次顯示該表單,這一次將在“有效”字段中顯示用戶輸入的數據,並顯示描述無效字段問題的消息。服務器收到包含所有有效表單數據的請求後,便可以執行適當的操作(例如,保存數據,返回搜索結果,上傳文件等),然後通知用戶。

- -

可以想像,創建HTML,驗證返回的數據,在需要時使用錯誤報告重新顯示輸入的數據以及對有效數據執行所需的操作都需要花費大量精力才能“正確”。 Django通過刪除一些繁瑣且重複的代碼,使此操作變得更加容易!

- -

Django表單處理流程

- -

Django的表單處理使用了我們在以前的教程中學到的所有相同技術(用於顯示有關模型的信息):視圖獲取請求,執行所需的任何操作,包括從模型中讀取數據,然後生成並返回HTML頁面( 從模板中,我們傳遞一個包含要顯示的數據的上下文)。 使事情變得更加複雜的是,服務器還需要能夠處理用戶提供的數據,並在出現任何錯誤時重新顯示頁面。

- -

下面顯示了Django處理表單請求的過程流程圖,該流程圖從對包含表單的頁面的請求(以綠色顯示)開始。
- Updated form handling process doc.

- -

根據上圖,Django表單處理的主要功能是:

- -
    -
  1. 在用戶第一次請求時顯示默認表單。 -
      -
    • 該表單可能包含空白字段(例如,如果您正在創建新記錄),或者可能會預先填充有初始值(例如,如果您正在更改記錄或具有有用的默認初始值)。
    • -
    • 由於此表單與任何用戶輸入的數據均不相關(儘管它可能具有初始值),因此在這一點上被稱為未綁定。
    • -
    -
  2. -
  3. 從提交請求中接收數據並將其綁定到表單。 -
      -
    • 將數據綁定到表單意味著當我們需要重新顯示表單時,用戶輸入的數據和任何錯誤均可用。
    • -
    -
  4. -
  5. 清理並驗證數據。 -
      -
    • 清理數據會對輸入執行清理操作(例如,刪除可能用於向服務器發送惡意內容的無效字符),並將其轉換為一致的Python類型。
    • -
    • 驗證會檢查該值是否適合該字段(例如,日期範圍正確,時間不要太短或太長等)
    • -
    -
  6. -
  7. 如果任何數據無效,則這次重新顯示該表單,其中包含用戶填充的所有值和問題字段的錯誤消息。
  8. -
  9. 如果所有數據均有效,請執行所需的操作(例如,保存數據,發送和發送電子郵件,返回搜索結果,上傳文件等)
  10. -
  11. 完成所有操作後,將用戶重定向到另一個頁面。
  12. -
- -

Django提供了許多工具和方法來幫助您完成上述任務。 最基本的是 Form類,它簡化了表單HTML的生成和數據清除/驗證的過程。 在下一節中,我們將使用頁面的實際示例描述表單如何工作,以使圖書館員可以續訂書籍。

- -
-

注意: 當我們討論Django的更多“高級”表單框架類時,了解Form的使用方式將對您有所幫助。

-
- -

使用表單和功能視圖續訂表單

- -

接下來,我們將添加一個頁面,以使圖書館員可以續借借來的書。 為此,我們將創建一個允許用戶輸入日期值的表單。 我們將從當前日期(正常藉閱期)起3週內為該字段提供初始值,並添加一些驗證以確保館員不能輸入過去的日期或將來的日期。 輸入有效日期後,我們會將其寫入當前記錄的BookInstance.due_back 字段中。

- -

該示例將使用基於函數的視圖和Form 類。 以下各節說明表單的工作方式,以及您需要對正在進行的LocalLibrary項目進行的更改。

- -

Form

- -

Form類是Django表單處理系統的核心。 它指定表單中的字段,其佈局,顯示小部件,標籤,初始值,有效值,以及(一旦驗證)與無效字段關聯的錯誤消息。 該類還提供了使用預定義格式(表,列表等)在模板中呈現自身的方法,或用於獲取任何元素的值(啟用細粒度手動呈現)的方法。

- -

申報表格

- -

Form 的聲明語法與聲明Model的語法非常相似,並且具有相同的字段類型(和一些相似的參數)。 這是有道理的,因為在兩種情況下,我們都需要確保每個字段都處理正確的數據類型,被限制為有效數據並具有顯示/文檔描述。

- -

要創建一個表單,我們導入Form 庫,從Form 類派生,並聲明表單的字段。 下面顯示了我們的圖書館圖書續訂表格的一個非常基本的表格類:

- -
from django import forms
-
-class RenewBookForm(forms.Form):
-    renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).")
-
- -

Form fields

- -

In this case we have a single DateField for entering the renewal date that will render in HTML with a blank value, the default label "Renewal date:", and some helpful usage text: "Enter a date between now and 4 weeks (default 3 weeks)." As none of the other optional arguments are specified the field will accept dates using the input_formats: YYYY-MM-DD (2016-11-06), MM/DD/YYYY (02/26/2016), MM/DD/YY (10/25/16), and will be rendered using the default widget: DateInput.

- -

There are many other types of form fields, which you will largely recognise from their similarity to the equivalent model field classes: BooleanField, CharField, ChoiceField, TypedChoiceField, DateField, DateTimeField, DecimalField, DurationField, EmailField, FileField, FilePathField, FloatField, ImageField, IntegerField, GenericIPAddressField, MultipleChoiceField, TypedMultipleChoiceField, NullBooleanField, RegexField, SlugField, TimeField, URLField, UUIDField, ComboField, MultiValueField, SplitDateTimeField, ModelMultipleChoiceField, ModelChoiceField​​​​.

- -

The arguments that are common to most fields are listed below (these have sensible default values):

- -
    -
  • required: If True, the field may not be left blank or given a None value. Fields are required by default, so you would set required=False to allow blank values in the form.
  • -
  • label: The label to use when rendering the field in HTML. If label is not specified then Django would create one from the field name by capitalising the first letter and replacing underscores with spaces (e.g. Renewal date).
  • -
  • label_suffix: By default a colon is displayed after the label (e.g. Renewal date:). This argument allows you to specify a different suffix containing other character(s).
  • -
  • initial: The initial value for the field when the form is displayed.
  • -
  • widget: The display widget to use.
  • -
  • help_text (as seen in the example above): Additional text that can be displayed in forms to explain how to use the field.
  • -
  • error_messages: A list of error messages for the field. You can override these with your own messages if needed.
  • -
  • validators: A list of functions that will be called on the field when it is validated.
  • -
  • localize: Enables the localisation of form data input (see link for more information).
  • -
  • disabled: The field is displayed but its value cannot be edited if this is True. The default is False.
  • -
- -

Validation

- -

Django provides numerous places where you can validate your data. The easiest way to validate a single field is to override the method clean_<fieldname>() for the field you want to check. So for example, we can validate that entered renewal_date values are between now and 4 weeks by implementing clean_renewal_date() as shown below.

- -
from django import forms
-
-from django.core.exceptions import ValidationError
-from django.utils.translation import ugettext_lazy as _
-import datetime #for checking renewal date range.
-
-class RenewBookForm(forms.Form):
-    renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).")
-
-    def clean_renewal_date(self):
-        data = self.cleaned_data['renewal_date']
-
-        #Check date is not in past.
-        if data < datetime.date.today():
-            raise ValidationError(_('Invalid date - renewal in past'))
-
-        #Check date is in range librarian allowed to change (+4 weeks).
-        if data > datetime.date.today() + datetime.timedelta(weeks=4):
-            raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))
-
-        # Remember to always return the cleaned data.
-        return data
- -

There are two important things to note. The first is that we get our data using self.cleaned_data['renewal_date'] and that we return this data whether or not we change it at the end of the function. This step gets us the data "cleaned" and sanitised of potentially unsafe input using the default validators, and converted into the correct standard type for the data (in this case a Python datetime.datetime object).

- -

The second point is that if a value falls outside our range we raise a ValidationError, specifying the error text that we want to display in the form if an invalid value is entered. The example above also wraps this text in one of Django's translation functions ugettext_lazy() (imported as _()), which is good practice if you want to translate your site later.

- -
-

Note: There are numerious other methods and examples for validating forms in Form and field validation (Django docs). For example, in cases where you have multiple fields that depend on each other, you can override the Form.clean() function and again raise a ValidationError.

-
- -

That's all we need for the form in this example!

- -

Copy the Form

- -

Create and open the file locallibrary/catalog/forms.py and copy the entire code listing from the previous block into it.

- -

URL Configuration

- -

Before we create our view, let's add a URL configuration for the renew-books page. Copy the following configuration to the bottom of locallibrary/catalog/urls.py.

- -
urlpatterns += [
-    path('book/<uuid:pk>/renew/', views.renew_book_librarian, name='renew-book-librarian'),
-]
- -

The URL configuration will redirect URLs with the format /catalog/book/<bookinstance id>/renew/ to the function named renew_book_librarian() in views.py, and send the BookInstance id as the parameter named pk. The pattern only matches if pk is a correctly formatted uuid.

- -
-

Note: We can name our captured URL data "pk" anything we like, because we have complete control over the view function (we're not using a generic detail view class that expects parameters with a certain name). However pk, short for "primary key", is a reasonable convention to use!

-
- -

View

- -

As discussed in the Django form handling process above, the view has to render the default form when it is first called and then either re-render it with error messages if the data is invalid, or process the data and redirect to a new page if the data is valid. In order to perform these different actions, the view has to be able to know whether it is being called for the first time to render the default form, or a subsequent time to validate data.

- -

For forms that use a POST request to submit information to the server, the most common pattern is for the view to test against the POST request type (if request.method == 'POST':) to identify form validation requests and GET (using an else condition) to identify the initial form creation request. If you want to submit your data using a GET request then a typical approach for identifying whether this is the first or subsequent view invocation is to read the form data (e.g. to read a hidden value in the form).

- -

The book renewal process will be writing to our database, so by convention we use the POST request approach. The code fragment below shows the (very standard) pattern for this sort of function view.

- -
from django.shortcuts import get_object_or_404
-from django.http import HttpResponseRedirect
-from django.urls import reverse
-import datetime
-
-from .forms import RenewBookForm
-
-def renew_book_librarian(request, pk):
-    book_inst=get_object_or_404(BookInstance, pk = pk)
-
-    # If this is a POST request then process the Form data
-    if request.method == 'POST':
-
-        # Create a form instance and populate it with data from the request (binding):
-        form = RenewBookForm(request.POST)
-
-        # Check if the form is valid:
-        if form.is_valid():
-            # process the data in form.cleaned_data as required (here we just write it to the model due_back field)
-            book_inst.due_back = form.cleaned_data['renewal_date']
-            book_inst.save()
-
-            # redirect to a new URL:
-            return HttpResponseRedirect(reverse('all-borrowed') )
-
-    # If this is a GET (or any other method) create the default form.
-    else:
-        proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
-        form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,})
-
-    return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst})
- -

First we import our form (RenewBookForm) and a number of other useful objects/methods used in the body of the view function:

- -
    -
  • get_object_or_404(): Returns a specified object from a model based on its primary key value, and raises an Http404 exception (not found) if the record does not exist.
  • -
  • HttpResponseRedirect: This creates a redirect to a specified URL (HTTP status code 302).
  • -
  • reverse(): This generates a URL from a URL configuration name and a set of arguments. It is the Python equivalent of the url tag that we've been using in our templates.
  • -
  • datetime: A Python library for manipulating dates and times.
  • -
- -

In the view we first use the pk argument in get_object_or_404() to get the current BookInstance (if this does not exist, the view will immediately exit and the page will display a "not found" error). If this is not a POST request (handled by the else clause) then we create the default form passing in an initial value for the renewal_date field (as shown in bold below, this is 3 weeks from the current date).

- -
    book_inst=get_object_or_404(BookInstance, pk = pk)
-
-    # If this is a GET (or any other method) create the default form
-    else:
-        proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
-        form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,})
-
-    return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst})
- -

After creating the form, we call render() to create the HTML page, specifying the template and a context that contains our form. In this case the context also contains our BookInstance, which we'll use in the template to provide information about the book we're renewing.

- -

If however this is a POST request, then we create our form object and populate it with data from the request. This process is called "binding" and allows us to validate the form. We then check if the form is valid, which runs all the validation code on all of the fields — including both the generic code to check that our date field is actually a valid date and our specific form's clean_renewal_date() function to check the date is in the right range.

- -
    book_inst=get_object_or_404(BookInstance, pk = pk)
-
-    # If this is a POST request then process the Form data
-    if request.method == 'POST':
-
-        # Create a form instance and populate it with data from the request (binding):
-        form = RenewBookForm(request.POST)
-
-        # Check if the form is valid:
-        if form.is_valid():
-            # process the data in form.cleaned_data as required (here we just write it to the model due_back field)
-            book_inst.due_back = form.cleaned_data['renewal_date']
-            book_inst.save()
-
-            # redirect to a new URL:
-            return HttpResponseRedirect(reverse('all-borrowed') )
-
-    return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst})
- -

If the form is not valid we call render() again, but this time the form value passed in the context will include error messages.

- -

If the form is valid, then we can start to use the data, accessing it through the form.cleaned_data attribute (e.g. data = form.cleaned_data['renewal_date']). Here we just save the data into the due_back value of the associated BookInstance object.

- -
-

Important: While you can also access the form data directly through the request (for example request.POST['renewal_date'] or request.GET['renewal_date'] (if using a GET request) this is NOT recommended. The cleaned data is sanitised, validated, and converted into Python-friendly types.

-
- -

The final step in the form-handling part of the view is to redirect to another page, usually a "success" page. In this case we use HttpResponseRedirect and reverse() to redirect to the view named 'all-borrowed' (this was created as the "challenge" in Django Tutorial Part 8: User authentication and permissions). If you didn't create that page consider redirecting to the home page at URL '/').

- -

That's everything needed for the form handling itself, but we still need to restrict access to the view to librarians. We should probably create a new permission in BookInstance ("can_renew"), but to keep things simple here we just use the @permission_required function decorator with our existing can_mark_returned permission.

- -

The final view is therefore as shown below. Please copy this into the bottom of locallibrary/catalog/views.py.

- -
from django.contrib.auth.decorators import permission_required
-
-from django.shortcuts import get_object_or_404
-from django.http import HttpResponseRedirect
-from django.urls import reverse
-import datetime
-
-from .forms import RenewBookForm
-
-@permission_required('catalog.can_mark_returned')
-def renew_book_librarian(request, pk):
-    """
-    View function for renewing a specific BookInstance by librarian
-    """
-    book_inst=get_object_or_404(BookInstance, pk = pk)
-
-    # If this is a POST request then process the Form data
-    if request.method == 'POST':
-
-        # Create a form instance and populate it with data from the request (binding):
-        form = RenewBookForm(request.POST)
-
-        # Check if the form is valid:
-        if form.is_valid():
-            # process the data in form.cleaned_data as required (here we just write it to the model due_back field)
-            book_inst.due_back = form.cleaned_data['renewal_date']
-            book_inst.save()
-
-            # redirect to a new URL:
-            return HttpResponseRedirect(reverse('all-borrowed') )
-
-    # If this is a GET (or any other method) create the default form.
-    else:
-        proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
-        form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,})
-
-    return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst})
-
- -

The template

- -

Create the template referenced in the view (/catalog/templates/catalog/book_renew_librarian.html) and copy the code below into it:

- -
{% extends "base_generic.html" %}
-{% block content %}
-
-    <h1>Renew: \{{bookinst.book.title}}</h1>
-    <p>Borrower: \{{bookinst.borrower}}</p>
-    <p{% if bookinst.is_overdue %} class="text-danger"{% endif %}>Due date: \{{bookinst.due_back}}</p>
-
-    <form action="" method="post">
-        {% csrf_token %}
-        <table>
-        \{{ form }}
-        </table>
-        <input type="submit" value="Submit" />
-    </form>
-
-{% endblock %}
- -

Most of this will be completely familiar from previous tutorials. We extend the base template and then redefine the content block. We are able to reference \{{bookinst}} (and its variables) because it was passed into the context object in the render() function, and we use these to list the book title, borrower and the original due date.

- -

The form code is relatively simple. First we declare the form tags, specifying where the form is to be submitted (action) and the method for submitting the data (in this case an "HTTP POST") — if you recall the HTML Forms overview at the top of the page, an empty action as shown, means that the form data will be posted back to the current URL of the page (which is what we want!). Inside the tags we define the submit input, which a user can press to submit the data. The {% csrf_token %} added just inside the form tags is part of Django's cross-site forgery protection.

- -
-

Note: Add the {% csrf_token %} to every Django template you create that uses POST to submit data. This will reduce the chance of forms being hijacked by malicious users.

-
- -

All that's left is the \{{form}} template variable, which we passed to the template in the context dictionary. Perhaps unsurprisingly, when used as shown this provides the default rendering of all the form fields, including their labels, widgets, and help text — the rendering is as shown below:

- -
<tr>
-  <th><label for="id_renewal_date">Renewal date:</label></th>
-  <td>
-    <input id="id_renewal_date" name="renewal_date" type="text" value="2016-11-08" required />
-    <br />
-    <span class="helptext">Enter date between now and 4 weeks (default 3 weeks).</span>
-  </td>
-</tr>
-
- -
-

Note: It is perhaps not obvious because we only have one field, but by default every field is defined in its own table row (which is why the variable is inside table tags above).​​​​​​ This same rendering is provided if you reference the template variable \{{ form.as_table }}.

-
- -

If you were to enter an invalid date, you'd additionally get a list of the errors rendered in the page (shown in bold below).

- -
<tr>
-  <th><label for="id_renewal_date">Renewal date:</label></th>
-   <td>
-      <ul class="errorlist">
-        <li>Invalid date - renewal in past</li>
-      </ul>
-      <input id="id_renewal_date" name="renewal_date" type="text" value="2015-11-08" required />
-      <br />
-      <span class="helptext">Enter date between now and 4 weeks (default 3 weeks).</span>
-    </td>
-</tr>
- -

Other ways of using form template variable

- -

Using \{{form}} as shown above, each field is rendered as a table row. You can also render each field as a list item (using \{{form.as_ul}} ) or as a paragraph (using \{{form.as_p}}).

- -

What is even more cool is that you can have complete control over the rendering of each part of the form, by indexing its properties using dot notation. So for example we can access a number of separate items for our renewal_date field:

- -
    -
  • \{{form.renewal_date}}: The whole field.
  • -
  • \{{form.renewal_date.errors}}: The list of errors.
  • -
  • \{{form.renewal_date.id_for_label}}: The id of the label.
  • -
  • \{{form.renewal_date.help_text}}: The field help text.
  • -
  • etc!
  • -
- -

For more examples of how to manually render forms in templates and dynamically loop over template fields, see Working with forms > Rendering fields manually (Django docs).

- -

Testing the page

- -

If you accepted the "challenge" in Django Tutorial Part 8: User authentication and permissions you'll have a list of all books on loan in the library, which is only visible to library staff. We can add a link to our renew page next to each item using the template code below.

- -
{% if perms.catalog.can_mark_returned %}- <a href="{% url 'renew-book-librarian' bookinst.id %}">Renew</a>  {% endif %}
- -
-

Note: Remember that your test login will need to have the permission "catalog.can_mark_returned" in order to access the renew book page (perhaps use your superuser account).

-
- -

You can alternatively manually construct a test URL like this — http://127.0.0.1:8000/catalog/book/<bookinstance_id>/renew/ (a valid bookinstance id can be obtained by navigating to a book detail page in your library, and copying the id field).

- -

What does it look like?

- -

If you are successful, the default form will look like this:

- -

- -

The form with an invalid value entered, will look like this:

- -

- -

The list of all books with renew links will look like this:

- -

- -

ModelForms

- -

Creating a Form class using the approach described above is very flexible, allowing you to create whatever sort of form page you like and associate it with any model or models.

- -

However if you just need a form to map the fields of a single model then your model will already define most of the information that you need in your form: fields, labels, help text, etc. Rather than recreating the model definitions in your form, it is easier to use the ModelForm helper class to create the form from your model. This ModelForm can then be used within your views in exactly the same way as an ordinary Form.

- -

A basic ModelForm containing the same field as our original RenewBookForm is shown below. All you need to do to create the form is add class Meta with the associated model (BookInstance) and a list of the model fields to include in the form (you can include all fields using fields = '__all__', or you can use exclude (instead of fields) to specify the fields not to include from the model).

- -
from django.forms import ModelForm
-from .models import BookInstance
-
-class RenewBookModelForm(ModelForm):
-    class Meta:
-        model = BookInstance
-        fields = ['due_back',]
-
- -
-

Note: This might not look like all that much simpler than just using a Form (and it isn't in this case, because we just have one field). However if you have a lot of fields, it can reduce the amount of code quite significantly!

-
- -

The rest of the information comes from the model field definitions (e.g. labels, widgets, help text, error messages). If these aren't quite right, then we can override them in our class Meta, specifying a dictionary containing the field to change and its new value. For example, in this form we might want a label for our field of "Renewal date" (rather than the default based on the field name: Due date), and we also want our help text to be specific to this use case. The Meta below shows you how to override these fields, and you can similarly set widgets and error_messages if the defaults aren't sufficient.

- -
class Meta:
-    model = BookInstance
-    fields = ['due_back',]
-    labels = { 'due_back': _('Renewal date'), }
-    help_texts = { 'due_back': _('Enter a date between now and 4 weeks (default 3).'), } 
-
- -

To add validation you can use the same approach as for a normal Form — you define a function named clean_field_name() and raise ValidationError exceptions for invalid values. The only difference with respect to our original form is that the model field is named due_back and not "renewal_date".

- -
from django.forms import ModelForm
-from .models import BookInstance
-
-class RenewBookModelForm(ModelForm):
-    def clean_due_back(self):
-       data = self.cleaned_data['due_back']
-
-       #Check date is not in past.
-       if data < datetime.date.today():
-           raise ValidationError(_('Invalid date - renewal in past'))
-
-       #Check date is in range librarian allowed to change (+4 weeks)
-       if data > datetime.date.today() + datetime.timedelta(weeks=4):
-           raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))
-
-       # Remember to always return the cleaned data.
-       return data
-
-    class Meta:
-        model = BookInstance
-        fields = ['due_back',]
-        labels = { 'due_back': _('Renewal date'), }
-        help_texts = { 'due_back': _('Enter a date between now and 4 weeks (default 3).'), }
-
- -

The class RenewBookModelForm below is now functionally equivalent to our original RenewBookForm. You could import and use it wherever you currently use RenewBookForm.

- -

Generic editing views

- -

The form handling algorithm we used in our function view example above represents an extremely common pattern in form editing views. Django abstracts much of this "boilerplate" for you, by creating generic editing views for creating, editing, and deleting views based on models. Not only do these handle the "view" behaviour, but they automatically create the form class (a ModelForm) for you from the model.

- -
-

Note: In addition to the editing views described here, there is also a FormView class, which lies somewhere between our function view and the other generic views in terms of "flexibility" vs "coding effort". Using FormView you still need to create your Form, but you don't have to implement all of the standard form-handling pattern. Instead you just have to provide an implementation of the function that will be called once the submitted is known to be be valid.

-
- -

In this section we're going to use generic editing views to create pages to add functionality to create, edit, and delete Author records from our library — effectively providing a basic reimplementation of parts of the Admin site (this could be useful if you need to offer admin functionality in a more flexible way that can be provided by the admin site).

- -

Views

- -

Open the views file (locallibrary/catalog/views.py) and append the following code block to the bottom of it:

- -
from django.views.generic.edit import CreateView, UpdateView, DeleteView
-from django.urls import reverse_lazy
-from .models import Author
-
-class AuthorCreate(CreateView):
-    model = Author
-    fields = '__all__'
-    initial={'date_of_death':'05/01/2018',}
-
-class AuthorUpdate(UpdateView):
-    model = Author
-    fields = ['first_name','last_name','date_of_birth','date_of_death']
-
-class AuthorDelete(DeleteView):
-    model = Author
-    success_url = reverse_lazy('authors')
- -

As you can see, to create the views you need to derive from CreateView, UpdateView, and DeleteView (respectively) and then define the associated model.

- -

For the "create" and "update" cases you also need to specify the fields to display in the form (using in same syntax as for ModelForm). In this case we show both the syntax to display "all" fields, and how you can list them individually. You can also specify initial values for each of the fields using a dictionary of field_name/value pairs (here we arbitrarily set the date of death for demonstration purposes — you might want to remove that!). By default these views will redirect on success to a page displaying the newly created/edited model item, which in our case will be the author detail view we created in a previous tutorial. You can specify an alternative redirect location by explicitly declaring parameter success_url (as done for the AuthorDelete class).

- -

The AuthorDelete class doesn't need to display any of the fields, so these don't need to be specified. You do however need to specify the success_url, because there is no obvious default value for Django to use. In this case we use the reverse_lazy() function to redirect to our author list after an author has been deleted — reverse_lazy() is a lazily executed version of reverse(), used here because we're providing a URL to a class-based view attribute.

- -

Templates

- -

The "create" and "update" views use the same template by default, which will be named after your model: model_name_form.html (you can change the suffix to something other than _form using the template_name_suffix field in your view, e.g. template_name_suffix = '_other_suffix')

- -

Create the template file locallibrary/catalog/templates/catalog/author_form.html and copy in the text below.

- -
{% extends "base_generic.html" %}
-
-{% block content %}
-
-<form action="" method="post">
-    {% csrf_token %}
-    <table>
-    \{{ form.as_table }}
-    </table>
-    <input type="submit" value="Submit" />
-
-</form>
-{% endblock %}
- -

This is similar to our previous forms, and renders the fields using a table. Note also how again we declare the {% csrf_token %} to ensure that our forms are resistant to CSRF attacks.

- -

The "delete" view expects to find a template named with the format model_name_confirm_delete.html (again, you can change the suffix using template_name_suffix in your view). Create the template file locallibrary/catalog/templates/catalog/author_confirm_delete.html and copy in the text below.

- -
{% extends "base_generic.html" %}
-
-{% block content %}
-
-<h1>Delete Author</h1>
-
-<p>Are you sure you want to delete the author: \{{ author }}?</p>
-
-<form action="" method="POST">
-  {% csrf_token %}
-  <input type="submit" action="" value="Yes, delete." />
-</form>
-
-{% endblock %}
-
- -

URL configurations

- -

Open your URL configuration file (locallibrary/catalog/urls.py) and add the following configuration to the bottom of the file:

- -
urlpatterns += [
-    path('author/create/', views.AuthorCreate.as_view(), name='author_create'),
-    path('author/<int:pk>/update/', views.AuthorUpdate.as_view(), name='author_update'),
-    path('author/<int:pk>/delete/', views.AuthorDelete.as_view(), name='author_delete'),
-]
- -

There is nothing particularly new here! You can see that the views are classes, and must hence be called via .as_view(), and you should be able to recognise the URL patterns in each case. We must use pk as the name for our captured primary key value, as this is the parameter name expected by the view classes.

- -

The author create, update, and delete pages are now ready to test (we won't bother hooking them into the site sidebar in this case, although you can do so if you wish).

- -
-

Note: Observant users will have noticed that we didn't do anything to prevent unauthorised users from accessing the pages! We leave that as an exercise for you (hint: you could use the PermissionRequiredMixin and either create a new permission or reuse our can_mark_returned permission).

-
- -

Testing the page

- -

First login to the site with an account that has whatever permissions you decided are needed to access the author editing pages.

- -

Then navigate to the author create page: http://127.0.0.1:8000/catalog/author/create/, which should look like the screenshot below.

- -

Form Example: Create Author

- -

Enter values for the fields and then press Submit to save the author record. You should now be taken to a detail view for your new author, with a URL of something like http://127.0.0.1:8000/catalog/author/10.

- -

You can test editing records by appending /update/ to the end of the detail view URL (e.g. http://127.0.0.1:8000/catalog/author/10/update/) — we don't show a screenshot, because it looks just like the "create" page!

- -

Last of all we can delete the page, by appending delete to the end of the author detail-view URL (e.g. http://127.0.0.1:8000/catalog/author/10/delete/). Django should display the delete page shown below. Press Yes, delete. to remove the record and be taken to the list of all authors.

- -

- -

Challenge yourself

- -

Create some forms to create, edit and delete Book records. You can use exactly the same structure as for Authors. If your book_form.html template is just a copy-renamed version of the author_form.html template, then the new "create book" page will look like the screenshot below:

- -

- -
    -
- -

Summary

- -

Creating and handling forms can be a complicated process! Django makes it much easier by providing programmatic mechanisms to declare, render and validate forms. Furthermore, Django provides generic form editing views that can do almost all the work to define pages that can create, edit, and delete records associated with a single model instance.

- -

There is a lot more that can be done with forms (check out our See also list below), but you should now understand how to add basic forms and form-handling code to your own websites.

- -

See also

- - - -

{{PreviousMenuNext("Learn/Server-side/Django/authentication_and_sessions", "Learn/Server-side/Django/Testing", "Learn/Server-side/Django")}}

- -

In this module

- - diff --git a/files/zh-tw/learn/server-side/django/forms/index.md b/files/zh-tw/learn/server-side/django/forms/index.md new file mode 100644 index 00000000000000..0c4a0da05c2198 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/forms/index.md @@ -0,0 +1,656 @@ +--- +title: 'Django Tutorial Part 9: Working with forms' +slug: Learn/Server-side/Django/Forms +translation_of: Learn/Server-side/Django/Forms +--- +{{LearnSidebar}}{{PreviousMenuNext("Learn/Server-side/Django/authentication_and_sessions", "Learn/Server-side/Django/Testing", "Learn/Server-side/Django")}} + +在本教程中,我們將向您展示,如何在 Django 中使用 HTML 表單,特別是編寫表單以創建,更新和刪除模型實例的最簡單方法。作為本演示的一部分,我們將擴展 [LocalLibrary ](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website)網站,以便圖書館員,可以使用我們自己的表單(而不是使用管理員應用程序)更新圖書,創建,更新和刪除作者。 + + + + + + + + + + + + +
前提: + 完成先前所有的教程, 包含 + Django Tutorial Part 8: User authentication and permissions. +
目的: + 了解如何製作表單來向用戶取得資訊並更新資料庫。了解通用類別表單編輯視圖 ( generic class-based form editing views ) + 能夠大幅簡化用於單一模型的表單製作。 +
+ +## 概述 + +[HTML 表單](/en-US/docs/Web/Guide/HTML/Forms)是網頁上的一組一個或多個字段/小組件,可用於從用戶收集信息以提交到服務器。 表單是一種用於收集用戶輸入的靈活機制,因為有合適的小部件可以輸入許多不同類型的數據,包括文本框,複選框,單選按鈕,日期選擇器等。表單也是與服務器共享數據的相對安全的方式, 因為它們允許我們在具有跨站點請求偽造保護的`POST` 請求中發送數據。 + +儘管到目前為止,本教程中尚未創建任何表單,但我們已經在 Django Admin 網站中遇到過這些表單-例如,下面的屏幕截圖顯示了一種用於編輯我們的[Book](/en-US/docs/Learn/Server-side/Django/Models) 模型的表單,該表單由許多選擇列表和 文字編輯器。 + +![Admin Site - Book Add](admin_book_add.png) + +使用表單可能會很複雜!開發人員需要為表單編寫 HTML,在服務器上(也可能在瀏覽器中)驗證並正確清理輸入的數據,使用錯誤消息重新發布表單以通知用戶任何無效字段,並在成功提交數據後處理數據,最後以某種方式回應用戶以表示成功。 Django 表單通過提供一個框架使您能夠以編程方式定義表單及其字段,然後使用這些對像生成表單 HTML 代碼並處理許多驗證和用戶交互,從而完成了所有這些步驟中的大量工作。 + +在本教程中,我們將向您展示創建和使用表單的幾種方法,尤其是通用編輯表單視圖如何顯著減少創建表單來操縱表單所需的工作量。楷模。在此過程中,我們將擴展本地圖書館應用程序,方法是添加一個允許圖書館員續訂圖書的表格,並創建頁面以創建,編輯和刪除圖書和作者(複製上面顯示的表格的基本版本以編輯圖書) )。 + +## HTML 表單 + +首先簡要介紹一下 [HTML Forms](/en-US/docs/Learn/HTML/Forms)。 考慮一個簡單的 HTML 表單,其中有一個用於輸入某些“團隊”名稱的文本字段及其相關標籤: + +![Simple name field example in HTML form](form_example_name_field.png) + +表單在 HTML 中定義為 `
...
` 標記內元素的集合,其中至少包含`type="submit"`.的`input`元素。 + +```html +
+ + + +
+``` + +雖然這裡只有一個用於輸入團隊名稱的文本字段,但是表單可以具有任意數量的其他輸入元素及其關聯的標籤。字段的`type` 屬性定義將顯示哪種小部件。字段的 `name` 和`id` 用於標識 JavaScript / CSS / HTML 中的字段,而 `value`定義該字段在首次顯示時的初始值。匹配的團隊標籤是使用`label` 標籤指定的(請參見上面的“輸入名稱”),其中的 `for` 字段包含相關`input`的`id` 值。 + +`submit` 輸入將顯示為一個按鈕(默認情況下),用戶可以按下該按鈕以將表單中所有其他輸入元素中的數據上載到服務器(在這種情況下,僅是`team_name`)。表單屬性定義用於發送數據的 HTTP`method` 以及服務器上數據的目的地(`action`): + +- `action`: 提交表單時,將數據發送到該資源/ URL 進行處理。如果未設置(或設置為空字符串),則表單將被提交回當前頁面 URL。 +- `method`: 用於發送數據的 HTTP 方法:post 或 get。 + + - 如果數據將導致服務器數據庫的更改,則應始終使用`POST` 方法,因為這樣可以使它更能抵抗跨站點的偽造請求攻擊。 + - `GET` 方法應僅用於不更改用戶數據的表單(例如搜索表單)。建議您在希望添加書籤或共享 URL 時使用。 + +服務器的角色是首先呈現初始表單狀態-包含空白字段,或預填充初始值。用戶按下“提交”按鈕後,服務器將從 Web 瀏覽器接收帶有值的表單數據,並且必須驗證信息。如果表單包含無效數據,則服務器應再次顯示該表單,這一次將在“有效”字段中顯示用戶輸入的數據,並顯示描述無效字段問題的消息。服務器收到包含所有有效表單數據的請求後,便可以執行適當的操作(例如,保存數據,返回搜索結果,上傳文件等),然後通知用戶。 + +可以想像,創建 HTML,驗證返回的數據,在需要時使用錯誤報告重新顯示輸入的數據以及對有效數據執行所需的操作都需要花費大量精力才能“正確”。 Django 通過刪除一些繁瑣且重複的代碼,使此操作變得更加容易! + +## Django 表單處理流程 + +Django 的表單處理使用了我們在以前的教程中學到的所有相同技術(用於顯示有關模型的信息):視圖獲取請求,執行所需的任何操作,包括從模型中讀取數據,然後生成並返回 HTML 頁面( 從模板中,我們傳遞一個包含要顯示的數據的上下文)。 使事情變得更加複雜的是,服務器還需要能夠處理用戶提供的數據,並在出現任何錯誤時重新顯示頁面。 + +下面顯示了 Django 處理表單請求的過程流程圖,該流程圖從對包含表單的頁面的請求(以綠色顯示)開始。 +![Updated form handling process doc.](form_handling_-_standard.png) + +根據上圖,Django 表單處理的主要功能是: + +1. 在用戶第一次請求時顯示默認表單。 + + - 該表單可能包含空白字段(例如,如果您正在創建新記錄),或者可能會預先填充有初始值(例如,如果您正在更改記錄或具有有用的默認初始值)。 + - 由於此表單與任何用戶輸入的數據均不相關(儘管它可能具有初始值),因此在這一點上被稱為未綁定。 + +2. 從提交請求中接收數據並將其綁定到表單。 + + - 將數據綁定到表單意味著當我們需要重新顯示表單時,用戶輸入的數據和任何錯誤均可用。 + +3. 清理並驗證數據。 + + - 清理數據會對輸入執行清理操作(例如,刪除可能用於向服務器發送惡意內容的無效字符),並將其轉換為一致的 Python 類型。 + - 驗證會檢查該值是否適合該字段(例如,日期範圍正確,時間不要太短或太長等) + +4. 如果任何數據無效,則這次重新顯示該表單,其中包含用戶填充的所有值和問題字段的錯誤消息。 +5. 如果所有數據均有效,請執行所需的操作(例如,保存數據,發送和發送電子郵件,返回搜索結果,上傳文件等) +6. 完成所有操作後,將用戶重定向到另一個頁面。 + +Django 提供了許多工具和方法來幫助您完成上述任務。 最基本的是 `Form`類,它簡化了表單 HTML 的生成和數據清除/驗證的過程。 在下一節中,我們將使用頁面的實際示例描述表單如何工作,以使圖書館員可以續訂書籍。 + +> **備註:** 當我們討論 Django 的更多“高級”表單框架類時,了解`Form`的使用方式將對您有所幫助。 + +## 使用表單和功能視圖續訂表單 + +接下來,我們將添加一個頁面,以使圖書館員可以續借借來的書。 為此,我們將創建一個允許用戶輸入日期值的表單。 我們將從當前日期(正常藉閱期)起 3 週內為該字段提供初始值,並添加一些驗證以確保館員不能輸入過去的日期或將來的日期。 輸入有效日期後,我們會將其寫入當前記錄的`BookInstance.due_back` 字段中。 + +該示例將使用基於函數的視圖和`Form` 類。 以下各節說明表單的工作方式,以及您需要對正在進行的 LocalLibrary 項目進行的更改。 + +### Form + +`Form`類是 Django 表單處理系統的核心。 它指定表單中的字段,其佈局,顯示小部件,標籤,初始值,有效值,以及(一旦驗證)與無效字段關聯的錯誤消息。 該類還提供了使用預定義格式(表,列表等)在模板中呈現自身的方法,或用於獲取任何元素的值(啟用細粒度手動呈現)的方法。 + +#### 申報表格 + +`Form` 的聲明語法與聲明`Model`的語法非常相似,並且具有相同的字段類型(和一些相似的參數)。 這是有道理的,因為在兩種情況下,我們都需要確保每個字段都處理正確的數據類型,被限制為有效數據並具有顯示/文檔描述。 + +要創建一個表單,我們導入`Form` 庫,從`Form` 類派生,並聲明表單的字段。 下面顯示了我們的圖書館圖書續訂表格的一個非常基本的表格類: + +```python +from django import forms + +class RenewBookForm(forms.Form): + renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).") +``` + +#### Form fields + +In this case we have a single [`DateField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#datefield) for entering the renewal date that will render in HTML with a blank value, the default label "_Renewal date:_", and some helpful usage text: "_Enter a date between now and 4 weeks (default 3 weeks)._" As none of the other optional arguments are specified the field will accept dates using the [input_formats](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#django.forms.DateField.input_formats): YYYY-MM-DD (2016-11-06), MM/DD/YYYY (02/26/2016), MM/DD/YY (10/25/16), and will be rendered using the default [widget](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#widget): [DateInput](https://docs.djangoproject.com/en/2.0/ref/forms/widgets/#django.forms.DateInput). + +There are many other types of form fields, which you will largely recognise from their similarity to the equivalent model field classes: [`BooleanField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#booleanfield), [`CharField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#charfield), [`ChoiceField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#choicefield), [`TypedChoiceField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#typedchoicefield), [`DateField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#datefield), [`DateTimeField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#datetimefield), [`DecimalField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#decimalfield), [`DurationField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#durationfield), [`EmailField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#emailfield), [`FileField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#filefield), [`FilePathField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#filepathfield), [`FloatField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#floatfield), [`ImageField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#imagefield), [`IntegerField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#integerfield), [`GenericIPAddressField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#genericipaddressfield), [`MultipleChoiceField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#multiplechoicefield), [`TypedMultipleChoiceField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#typedmultiplechoicefield), [`NullBooleanField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#nullbooleanfield), [`RegexField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#regexfield), [`SlugField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#slugfield), [`TimeField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#timefield), [`URLField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#urlfield), [`UUIDField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#uuidfield), [`ComboField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#combofield), [`MultiValueField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#multivaluefield), [`SplitDateTimeField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#splitdatetimefield), [`ModelMultipleChoiceField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#modelmultiplechoicefield), [`ModelChoiceField`](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#modelchoicefield)​​​​. + +The arguments that are common to most fields are listed below (these have sensible default values): + +- [required](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#required): If `True`, the field may not be left blank or given a `None` value. Fields are required by default, so you would set `required=False` to allow blank values in the form. +- [label](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#label): The label to use when rendering the field in HTML. If [label](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#label) is not specified then Django would create one from the field name by capitalising the first letter and replacing underscores with spaces (e.g. _Renewal date_). +- [label_suffix](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#label-suffix): By default a colon is displayed after the label (e.g. Renewal date**:**). This argument allows you to specify a different suffix containing other character(s). +- [initial](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#initial): The initial value for the field when the form is displayed. +- [widget](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#widget): The display widget to use. +- [help_text](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#help-text) (as seen in the example above): Additional text that can be displayed in forms to explain how to use the field. +- [error_messages](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#error-messages): A list of error messages for the field. You can override these with your own messages if needed. +- [validators](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#validators): A list of functions that will be called on the field when it is validated. +- [localize](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#localize): Enables the localisation of form data input (see link for more information). +- [disabled](https://docs.djangoproject.com/en/2.0/ref/forms/fields/#disabled): The field is displayed but its value cannot be edited if this is `True`. The default is `False`. + +#### Validation + +Django provides numerous places where you can validate your data. The easiest way to validate a single field is to override the method `clean_()` for the field you want to check. So for example, we can validate that entered `renewal_date` values are between now and 4 weeks by implementing `clean_renewal_date() `as shown below. + +```python +from django import forms + +from django.core.exceptions import ValidationError +from django.utils.translation import ugettext_lazy as _ +import datetime #for checking renewal date range. + +class RenewBookForm(forms.Form): + renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).") + + def clean_renewal_date(self): + data = self.cleaned_data['renewal_date'] + + #Check date is not in past. + if data < datetime.date.today(): + raise ValidationError(_('Invalid date - renewal in past')) + + #Check date is in range librarian allowed to change (+4 weeks). + if data > datetime.date.today() + datetime.timedelta(weeks=4): + raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead')) + + # Remember to always return the cleaned data. + return data +``` + +There are two important things to note. The first is that we get our data using `self.cleaned_data['renewal_date']` and that we return this data whether or not we change it at the end of the function. This step gets us the data "cleaned" and sanitised of potentially unsafe input using the default validators, and converted into the correct standard type for the data (in this case a Python `datetime.datetime` object). + +The second point is that if a value falls outside our range we raise a `ValidationError`, specifying the error text that we want to display in the form if an invalid value is entered. The example above also wraps this text in one of [Django's translation functions](https://docs.djangoproject.com/en/2.0/topics/i18n/translation/) `ugettext_lazy()` (imported as `_()`), which is good practice if you want to translate your site later. + +> **備註:** There are numerious other methods and examples for validating forms in [Form and field validation](https://docs.djangoproject.com/en/2.0/ref/forms/validation/) (Django docs). For example, in cases where you have multiple fields that depend on each other, you can override the [Form.clean()](https://docs.djangoproject.com/en/2.0/ref/forms/api/#django.forms.Form.clean) function and again raise a `ValidationError`. + +That's all we need for the form in this example! + +#### Copy the Form + +Create and open the file **locallibrary/catalog/forms.py** and copy the entire code listing from the previous block into it. + +### URL Configuration + +Before we create our view, let's add a URL configuration for the _renew-books_ page. Copy the following configuration to the bottom of **locallibrary/catalog/urls.py**. + +```python +urlpatterns += [ + path('book//renew/', views.renew_book_librarian, name='renew-book-librarian'), +] +``` + +The URL configuration will redirect URLs with the format **/catalog/book/_\_/renew/** to the function named `renew_book_librarian()` in **views.py**, and send the `BookInstance` id as the parameter named `pk`. The pattern only matches if `pk` is a correctly formatted `uuid`. + +> **備註:** We can name our captured URL data "`pk`" anything we like, because we have complete control over the view function (we're not using a generic detail view class that expects parameters with a certain name). However `pk`, short for "primary key", is a reasonable convention to use! + +### View + +As discussed in the [Django form handling process](#django_form_handling_process) above, the view has to render the default form when it is first called and then either re-render it with error messages if the data is invalid, or process the data and redirect to a new page if the data is valid. In order to perform these different actions, the view has to be able to know whether it is being called for the first time to render the default form, or a subsequent time to validate data. + +For forms that use a `POST` request to submit information to the server, the most common pattern is for the view to test against the `POST` request type (`if request.method == 'POST':`) to identify form validation requests and `GET` (using an `else` condition) to identify the initial form creation request. If you want to submit your data using a `GET` request then a typical approach for identifying whether this is the first or subsequent view invocation is to read the form data (e.g. to read a hidden value in the form). + +The book renewal process will be writing to our database, so by convention we use the `POST` request approach. The code fragment below shows the (very standard) pattern for this sort of function view. + +```python +from django.shortcuts import get_object_or_404 +from django.http import HttpResponseRedirect +from django.urls import reverse +import datetime + +from .forms import RenewBookForm + +def renew_book_librarian(request, pk): + book_inst=get_object_or_404(BookInstance, pk = pk) + + # If this is a POST request then process the Form data + if request.method == 'POST': + + # Create a form instance and populate it with data from the request (binding): + form = RenewBookForm(request.POST) + + # Check if the form is valid: + if form.is_valid(): + # process the data in form.cleaned_data as required (here we just write it to the model due_back field) + book_inst.due_back = form.cleaned_data['renewal_date'] + book_inst.save() + + # redirect to a new URL: + return HttpResponseRedirect(reverse('all-borrowed') ) + + # If this is a GET (or any other method) create the default form. + else: + proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) + form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,}) + + return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst}) +``` + +First we import our form (`RenewBookForm`) and a number of other useful objects/methods used in the body of the view function: + +- [`get_object_or_404()`](https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#get-object-or-404): Returns a specified object from a model based on its primary key value, and raises an `Http404` exception (not found) if the record does not exist. +- [`HttpResponseRedirect`](https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.HttpResponseRedirect): This creates a redirect to a specified URL (HTTP status code 302). +- [`reverse()`](https://docs.djangoproject.com/en/2.0/ref/urlresolvers/#django.urls.reverse): This generates a URL from a URL configuration name and a set of arguments. It is the Python equivalent of the `url` tag that we've been using in our templates. +- [`datetime`](https://docs.python.org/3/library/datetime.html): A Python library for manipulating dates and times. + +In the view we first use the `pk` argument in `get_object_or_404()` to get the current `BookInstance` (if this does not exist, the view will immediately exit and the page will display a "not found" error). If this is _not_ a `POST` request (handled by the `else` clause) then we create the default form passing in an `initial` value for the `renewal_date` field (as shown in bold below, this is 3 weeks from the current date). + +```python + book_inst=get_object_or_404(BookInstance, pk = pk) + + # If this is a GET (or any other method) create the default form + else: + proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) + form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,}) + + return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst}) +``` + +After creating the form, we call `render()` to create the HTML page, specifying the template and a context that contains our form. In this case the context also contains our `BookInstance`, which we'll use in the template to provide information about the book we're renewing. + +If however this is a `POST` request, then we create our `form` object and populate it with data from the request. This process is called "binding" and allows us to validate the form. We then check if the form is valid, which runs all the validation code on all of the fields — including both the generic code to check that our date field is actually a valid date and our specific form's `clean_renewal_date()` function to check the date is in the right range. + +```python + book_inst=get_object_or_404(BookInstance, pk = pk) + + # If this is a POST request then process the Form data + if request.method == 'POST': + + # Create a form instance and populate it with data from the request (binding): + form = RenewBookForm(request.POST) + + # Check if the form is valid: + if form.is_valid(): + # process the data in form.cleaned_data as required (here we just write it to the model due_back field) + book_inst.due_back = form.cleaned_data['renewal_date'] + book_inst.save() + + # redirect to a new URL: + return HttpResponseRedirect(reverse('all-borrowed') ) + + return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst}) +``` + +If the form is not valid we call `render()` again, but this time the form value passed in the context will include error messages. + +If the form is valid, then we can start to use the data, accessing it through the `form.cleaned_data` attribute (e.g. `data = form.cleaned_data['renewal_date']`). Here we just save the data into the `due_back` value of the associated `BookInstance` object. + +> **警告:** While you can also access the form data directly through the request (for example `request.POST['renewal_date']` or `request.GET['renewal_date']` (if using a GET request) this is NOT recommended. The cleaned data is sanitised, validated, and converted into Python-friendly types. + +The final step in the form-handling part of the view is to redirect to another page, usually a "success" page. In this case we use `HttpResponseRedirect` and `reverse()` to redirect to the view named `'all-borrowed'` (this was created as the "challenge" in [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/authentication_and_sessions#Challenge_yourself)). If you didn't create that page consider redirecting to the home page at URL '/'). + +That's everything needed for the form handling itself, but we still need to restrict access to the view to librarians. We should probably create a new permission in `BookInstance` ("`can_renew`"), but to keep things simple here we just use the `@permission_required` function decorator with our existing `can_mark_returned` permission. + +The final view is therefore as shown below. Please copy this into the bottom of **locallibrary/catalog/views.py**. + + from django.contrib.auth.decorators import permission_required + + from django.shortcuts import get_object_or_404 + from django.http import HttpResponseRedirect + from django.urls import reverse + import datetime + + from .forms import RenewBookForm + + @permission_required('catalog.can_mark_returned') + def renew_book_librarian(request, pk): + """ + View function for renewing a specific BookInstance by librarian + """ + book_inst=get_object_or_404(BookInstance, pk = pk) + + # If this is a POST request then process the Form data + if request.method == 'POST': + + # Create a form instance and populate it with data from the request (binding): + form = RenewBookForm(request.POST) + + # Check if the form is valid: + if form.is_valid(): + # process the data in form.cleaned_data as required (here we just write it to the model due_back field) + book_inst.due_back = form.cleaned_data['renewal_date'] + book_inst.save() + + # redirect to a new URL: + return HttpResponseRedirect(reverse('all-borrowed') ) + + # If this is a GET (or any other method) create the default form. + else: + proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) + form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,}) + + return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst}) + +### The template + +Create the template referenced in the view (**/catalog/templates/catalog/book_renew_librarian.html**) and copy the code below into it: + +```html +{% extends "base_generic.html" %} +{% block content %} + +

Renew: \{{bookinst.book.title}}

+

Borrower: \{{bookinst.borrower}}

+ Due date: \{{bookinst.due_back}}

+ +
+ {% csrf_token %} + + \{{ form }} +
+ +
+ +{% endblock %} +``` + +Most of this will be completely familiar from previous tutorials. We extend the base template and then redefine the content block. We are able to reference `\{{bookinst}}` (and its variables) because it was passed into the context object in the `render()` function, and we use these to list the book title, borrower and the original due date. + +The form code is relatively simple. First we declare the `form` tags, specifying where the form is to be submitted (`action`) and the `method` for submitting the data (in this case an "HTTP POST") — if you recall the [HTML Forms](#HTML_forms) overview at the top of the page, an empty `action` as shown, means that the form data will be posted back to the current URL of the page (which is what we want!). Inside the tags we define the `submit` input, which a user can press to submit the data. The `{% csrf_token %}` added just inside the form tags is part of Django's cross-site forgery protection. + +> **備註:** Add the `{% csrf_token %}` to every Django template you create that uses `POST` to submit data. This will reduce the chance of forms being hijacked by malicious users. + +All that's left is the `\{{form}}` template variable, which we passed to the template in the context dictionary. Perhaps unsurprisingly, when used as shown this provides the default rendering of all the form fields, including their labels, widgets, and help text — the rendering is as shown below: + +```html + + + + +
+ Enter date between now and 4 weeks (default 3 weeks). + + +``` + +> **備註:** It is perhaps not obvious because we only have one field, but by default every field is defined in its own table row (which is why the variable is inside `table `tags above).​​​​​​ This same rendering is provided if you reference the template variable `\{{ form.as_table }}`. + +If you were to enter an invalid date, you'd additionally get a list of the errors rendered in the page (shown in bold below). + +```html + + + +
    +
  • Invalid date - renewal in past
  • +
+ +
+ Enter date between now and 4 weeks (default 3 weeks). + + +``` + +#### Other ways of using form template variable + +Using `\{{form}}` as shown above, each field is rendered as a table row. You can also render each field as a list item (using `\{{form.as_ul}}` ) or as a paragraph (using `\{{form.as_p}}`). + +What is even more cool is that you can have complete control over the rendering of each part of the form, by indexing its properties using dot notation. So for example we can access a number of separate items for our `renewal_date` field: + +- `\{{form.renewal_date}}:` The whole field. +- `\{{form.renewal_date.errors}}`: The list of errors. +- `\{{form.renewal_date.id_for_label}}`: The id of the label. +- `\{{form.renewal_date.help_text}}`: The field help text. +- etc! + +For more examples of how to manually render forms in templates and dynamically loop over template fields, see [Working with forms > Rendering fields manually](https://docs.djangoproject.com/en/2.0/topics/forms/#rendering-fields-manually) (Django docs). + +### Testing the page + +If you accepted the "challenge" in [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/authentication_and_sessions#Challenge_yourself) you'll have a list of all books on loan in the library, which is only visible to library staff. We can add a link to our renew page next to each item using the template code below. + +```html +{% if perms.catalog.can_mark_returned %}- Renew {% endif %} +``` + +> **備註:** Remember that your test login will need to have the permission "`catalog.can_mark_returned`" in order to access the renew book page (perhaps use your superuser account). + +You can alternatively manually construct a test URL like this — [http://127.0.0.1:8000/catalog/book/*\*/renew/](/renew/>) (a valid bookinstance id can be obtained by navigating to a book detail page in your library, and copying the `id` field). + +### What does it look like? + +If you are successful, the default form will look like this: + +![](forms_example_renew_default.png) + +The form with an invalid value entered, will look like this: + +![](forms_example_renew_invalid.png) + +The list of all books with renew links will look like this: + +![](forms_example_renew_allbooks.png) + +## ModelForms + +Creating a `Form` class using the approach described above is very flexible, allowing you to create whatever sort of form page you like and associate it with any model or models. + +However if you just need a form to map the fields of a _single_ model then your model will already define most of the information that you need in your form: fields, labels, help text, etc. Rather than recreating the model definitions in your form, it is easier to use the [ModelForm](https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/) helper class to create the form from your model. This `ModelForm` can then be used within your views in exactly the same way as an ordinary `Form`. + +A basic `ModelForm` containing the same field as our original `RenewBookForm` is shown below. All you need to do to create the form is add `class Meta` with the associated `model` (`BookInstance`) and a list of the model `fields` to include in the form (you can include all fields using `fields = '__all__'`, or you can use `exclude` (instead of `fields`) to specify the fields _not_ to include from the model). + +```python +from django.forms import ModelForm +from .models import BookInstance + +class RenewBookModelForm(ModelForm): + class Meta: + model = BookInstance + fields = ['due_back',] +``` + +> **備註:** This might not look like all that much simpler than just using a `Form` (and it isn't in this case, because we just have one field). However if you have a lot of fields, it can reduce the amount of code quite significantly! + +The rest of the information comes from the model field definitions (e.g. labels, widgets, help text, error messages). If these aren't quite right, then we can override them in our `class Meta`, specifying a dictionary containing the field to change and its new value. For example, in this form we might want a label for our field of "_Renewal date_" (rather than the default based on the field name: _Due date_), and we also want our help text to be specific to this use case. The `Meta` below shows you how to override these fields, and you can similarly set `widgets` and `error_messages` if the defaults aren't sufficient. + +```python +class Meta: + model = BookInstance + fields = ['due_back',] + labels = { 'due_back': _('Renewal date'), } + help_texts = { 'due_back': _('Enter a date between now and 4 weeks (default 3).'), } +``` + +To add validation you can use the same approach as for a normal `Form` — you define a function named `clean_field_name()` and raise `ValidationError` exceptions for invalid values. The only difference with respect to our original form is that the model field is named `due_back` and not "`renewal_date`". + +```python +from django.forms import ModelForm +from .models import BookInstance + +class RenewBookModelForm(ModelForm): + def clean_due_back(self): + data = self.cleaned_data['due_back'] + + #Check date is not in past. + if data < datetime.date.today(): + raise ValidationError(_('Invalid date - renewal in past')) + + #Check date is in range librarian allowed to change (+4 weeks) + if data > datetime.date.today() + datetime.timedelta(weeks=4): + raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead')) + + # Remember to always return the cleaned data. + return data + + class Meta: + model = BookInstance + fields = ['due_back',] + labels = { 'due_back': _('Renewal date'), } + help_texts = { 'due_back': _('Enter a date between now and 4 weeks (default 3).'), } +``` + +The class `RenewBookModelForm` below is now functionally equivalent to our original `RenewBookForm`. You could import and use it wherever you currently use `RenewBookForm`. + +## Generic editing views + +The form handling algorithm we used in our function view example above represents an extremely common pattern in form editing views. Django abstracts much of this "boilerplate" for you, by creating [generic editing views](https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-editing/) for creating, editing, and deleting views based on models. Not only do these handle the "view" behaviour, but they automatically create the form class (a `ModelForm`) for you from the model. + +> **備註:** In addition to the editing views described here, there is also a [FormView](https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-editing/#formview) class, which lies somewhere between our function view and the other generic views in terms of "flexibility" vs "coding effort". Using `FormView` you still need to create your `Form`, but you don't have to implement all of the standard form-handling pattern. Instead you just have to provide an implementation of the function that will be called once the submitted is known to be be valid. + +In this section we're going to use generic editing views to create pages to add functionality to create, edit, and delete `Author` records from our library — effectively providing a basic reimplementation of parts of the Admin site (this could be useful if you need to offer admin functionality in a more flexible way that can be provided by the admin site). + +### Views + +Open the views file (**locallibrary/catalog/views.py**) and append the following code block to the bottom of it: + +```python +from django.views.generic.edit import CreateView, UpdateView, DeleteView +from django.urls import reverse_lazy +from .models import Author + +class AuthorCreate(CreateView): + model = Author + fields = '__all__' + initial={'date_of_death':'05/01/2018',} + +class AuthorUpdate(UpdateView): + model = Author + fields = ['first_name','last_name','date_of_birth','date_of_death'] + +class AuthorDelete(DeleteView): + model = Author + success_url = reverse_lazy('authors') +``` + +As you can see, to create the views you need to derive from `CreateView`, `UpdateView`, and `DeleteView` (respectively) and then define the associated model. + +For the "create" and "update" cases you also need to specify the fields to display in the form (using in same syntax as for `ModelForm`). In this case we show both the syntax to display "all" fields, and how you can list them individually. You can also specify initial values for each of the fields using a dictionary of _field_name_/_value_ pairs (here we arbitrarily set the date of death for demonstration purposes — you might want to remove that!). By default these views will redirect on success to a page displaying the newly created/edited model item, which in our case will be the author detail view we created in a previous tutorial. You can specify an alternative redirect location by explicitly declaring parameter `success_url` (as done for the `AuthorDelete` class). + +The `AuthorDelete` class doesn't need to display any of the fields, so these don't need to be specified. You do however need to specify the `success_url`, because there is no obvious default value for Django to use. In this case we use the [`reverse_lazy()`](https://docs.djangoproject.com/en/2.0/ref/urlresolvers/#reverse-lazy) function to redirect to our author list after an author has been deleted — `reverse_lazy()` is a lazily executed version of `reverse()`, used here because we're providing a URL to a class-based view attribute. + +### Templates + +The "create" and "update" views use the same template by default, which will be named after your model: **model_name\_form.html** (you can change the suffix to something other than **\_form** using the `template_name_suffix` field in your view, e.g. `template_name_suffix = '_other_suffix'`) + +Create the template file **locallibrary/catalog/templates/catalog/author_form.html** and copy in the text below. + +```html +{% extends "base_generic.html" %} + +{% block content %} + +
+ {% csrf_token %} + + \{{ form.as_table }} +
+ + +
+{% endblock %} +``` + +This is similar to our previous forms, and renders the fields using a table. Note also how again we declare the `{% csrf_token %}` to ensure that our forms are resistant to CSRF attacks. + +The "delete" view expects to find a template named with the **format model_name\_confirm_delete.html** (again, you can change the suffix using `template_name_suffix` in your view). Create the template file **locallibrary/catalog/templates/catalog/author_confirm_delete.html** and copy in the text below. + +```html +{% extends "base_generic.html" %} + +{% block content %} + +

Delete Author

+ +

Are you sure you want to delete the author: \{{ author }}?

+ +
+ {% csrf_token %} + +
+ +{% endblock %} +``` + +### URL configurations + +Open your URL configuration file (**locallibrary/catalog/urls.py**) and add the following configuration to the bottom of the file: + +```python +urlpatterns += [ + path('author/create/', views.AuthorCreate.as_view(), name='author_create'), + path('author//update/', views.AuthorUpdate.as_view(), name='author_update'), + path('author//delete/', views.AuthorDelete.as_view(), name='author_delete'), +] +``` + +There is nothing particularly new here! You can see that the views are classes, and must hence be called via `.as_view()`, and you should be able to recognise the URL patterns in each case. We must use `pk` as the name for our captured primary key value, as this is the parameter name expected by the view classes. + +The author create, update, and delete pages are now ready to test (we won't bother hooking them into the site sidebar in this case, although you can do so if you wish). + +> **備註:** Observant users will have noticed that we didn't do anything to prevent unauthorised users from accessing the pages! We leave that as an exercise for you (hint: you could use the `PermissionRequiredMixin` and either create a new permission or reuse our `can_mark_returned` permission). + +### Testing the page + +First login to the site with an account that has whatever permissions you decided are needed to access the author editing pages. + +Then navigate to the author create page: , which should look like the screenshot below. + +![Form Example: Create Author](forms_example_create_author.png) + +Enter values for the fields and then press **Submit** to save the author record. You should now be taken to a detail view for your new author, with a URL of something like _http\://127.0.0.1:8000/catalog/author/10_. + +You can test editing records by appending _/update/_ to the end of the detail view URL (e.g. _http\://127.0.0.1:8000/catalog/author/10/update/_) — we don't show a screenshot, because it looks just like the "create" page! + +Last of all we can delete the page, by appending delete to the end of the author detail-view URL (e.g. _http\://127.0.0.1:8000/catalog/author/10/delete/_). Django should display the delete page shown below. Press **Yes, delete.** to remove the record and be taken to the list of all authors. + +![](forms_example_delete_author.png) + +## Challenge yourself + +Create some forms to create, edit and delete `Book` records. You can use exactly the same structure as for `Authors`. If your **book_form.html** template is just a copy-renamed version of the **author_form.html** template, then the new "create book" page will look like the screenshot below: + +![](forms_example_create_book.png) + +## Summary + +Creating and handling forms can be a complicated process! Django makes it much easier by providing programmatic mechanisms to declare, render and validate forms. Furthermore, Django provides generic form editing views that can do _almost all_ the work to define pages that can create, edit, and delete records associated with a single model instance. + +There is a lot more that can be done with forms (check out our See also list below), but you should now understand how to add basic forms and form-handling code to your own websites. + +## See also + +- [Working with forms](https://docs.djangoproject.com/en/2.0/topics/forms/) (Django docs) +- [Writing your first Django app, part 4 > Writing a simple form](https://docs.djangoproject.com/en/2.0/intro/tutorial04/#write-a-simple-form) (Django docs) +- [The Forms API](https://docs.djangoproject.com/en/2.0/ref/forms/api/) (Django docs) +- [Form fields](https://docs.djangoproject.com/en/2.0/ref/forms/fields/) (Django docs) +- [Form and field validation](https://docs.djangoproject.com/en/2.0/ref/forms/validation/) (Django docs) +- [Form handling with class-based views](https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-editing/) (Django docs) +- [Creating forms from models](https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/) (Django docs) +- [Generic editing views](https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-editing/) (Django docs) + +{{PreviousMenuNext("Learn/Server-side/Django/authentication_and_sessions", "Learn/Server-side/Django/Testing", "Learn/Server-side/Django")}} + +## In this module + +- [Django introduction](/en-US/docs/Learn/Server-side/Django/Introduction) +- [Setting up a Django development environment](/en-US/docs/Learn/Server-side/Django/development_environment) +- [Django Tutorial: The Local Library website](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django Tutorial Part 2: Creating a skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) +- [Django Tutorial Part 3: Using models](/en-US/docs/Learn/Server-side/Django/Models) +- [Django Tutorial Part 4: Django admin site](/en-US/docs/Learn/Server-side/Django/Admin_site) +- [Django Tutorial Part 5: Creating our home page](/en-US/docs/Learn/Server-side/Django/Home_page) +- [Django Tutorial Part 6: Generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views) +- [Django Tutorial Part 7: Sessions framework](/en-US/docs/Learn/Server-side/Django/Sessions) +- [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/Authentication) +- [Django Tutorial Part 9: Working with forms](/en-US/docs/Learn/Server-side/Django/Forms) +- [Django Tutorial Part 10: Testing a Django web application](/en-US/docs/Learn/Server-side/Django/Testing) +- [Django Tutorial Part 11: Deploying Django to production](/en-US/docs/Learn/Server-side/Django/Deployment) +- [Django web application security](/en-US/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django mini blog](/en-US/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/generic_views/index.html b/files/zh-tw/learn/server-side/django/generic_views/index.html deleted file mode 100644 index 43b55e8ac72f8a..00000000000000 --- a/files/zh-tw/learn/server-side/django/generic_views/index.html +++ /dev/null @@ -1,612 +0,0 @@ ---- -title: 'Django Tutorial Part 6: Generic list and detail views' -slug: Learn/Server-side/Django/Generic_views -translation_of: Learn/Server-side/Django/Generic_views ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Django/Home_page", "Learn/Server-side/Django/Sessions", "Learn/Server-side/Django")}}
- -

本教程擴充了 LocalLibrary 網站,為書本與作者增加列表與細節頁面。此處我們將學到通用類別視圖,並演示如何降低你必須為一般使用案例撰寫的程式碼數量。我們也會更加深入 URL 處理細節,演示如何實施基本模式匹配。

- - - - - - - - - - - - -
前提:Complete all previous tutorial topics, including Django Tutorial Part 5: Creating our home page.
目的:To understand where and how to use generic class-based views, and how to extract patterns from URLs and pass the information to views.
- -

Overview

- -

本教程中,通過為書本和作者添加列表和詳細信息頁面,我們將完成第一個版本的 LocalLibrary 網站(或者更準確地說,我們將向您展示如何實現書頁,並讓您自己創建作者頁面!) )

- -

該過程在創建索引頁面,我們在上一個教程中展示了該頁面。我們仍然需要創建URL地圖,視圖和模板。主要區別在於,對於詳細信息頁面,我們還有一個額外的挑戰,即從URL對於這些頁面,我們將演示一種完全不同的視圖類型:基於類別的通用列表和詳細視圖。這些可以顯著減少所需的視圖代碼量,有助於更容易編寫和維護。

- -

本教程的最後一部分,將演示在使用基於類別的通用列表視圖時,如何對數據進行分頁。

- -

Book list page

- -

該書將顯示每條記錄的標題和作者,標題是指向相關圖書詳細信息頁面的超鏈接。該頁面將具有與站點中,所有其他頁面相同的結構和導航,因此,我們可以擴展在上一個教程中創建的基本模板 (base_generic.html)。

- -

URL mapping

- -

開啟/catalog/urls.py,並複製加入下面粗體顯示的代碼。就像索引頁面的方式,這個path()函數,定義了一個與URL匹配的模式('books /'),如果URL匹配,將調用視圖函數(views.BookListView.as_view())和一個對應的特定映射的名稱。

- -
urlpatterns = [
-    path('', views.index, name='index'),
-    path('books/', views.BookListView.as_view(), name='books'),
-]
- -

正如前一個教程中所討論的,URL必須已經先匹配了/ catalog,因此實際上將為URL調用的視圖是:/ catalog / books /。

- -

我們將繼承現有的泛型視圖函數,該函數已經完成了我們希望此視圖函數執行的大部分工作,而不是從頭開始編寫自己的函數。對於基於Django類的視圖,我們通過調用類方法as_view(),來訪問適當的視圖函數。由此可以創建類的實例,並確保為HTTP請求正確的處理程序方法。

- -

View (class-based)

- -

我們可以很容易地,將書本列表列表編寫為常規函數(就像我們之前的索引視圖一樣),進入查詢數據庫中的所有書本,然後調用render(),將列表傳遞給指定的模板。然而,我們用另一種方​​法取代,我們將使用基於類的通用列表視圖(ListView)-一個繼承自現有視圖的類。因為通用視圖,已經實現了我們需要的大部分功能,並且遵循Django最佳實踐,我們將能夠創建更強大的列表視圖,代碼更多,重複次數最多,最終維護所需。

- -

開啟catalog / views.py,將以下代碼複製到文件的底部:

- -
from django.views import generic
-
-class BookListView(generic.ListView):
-    model = Book
- -

就是這樣!通用view將查詢數據庫,以獲取指定模型(Book)的所有記錄,然後呈現/locallibrary/catalog/templates/catalog/book_list.html的模板(我們將在下面創建)。在模板中,您可以使用所謂的object_list或book_list的模板變量(即通常為“ the_model_name_list”),以訪問書本列表。

- -
-

Note: This awkward path for the template location isn't a misprint — the generic views look for templates in /application_name/the_model_name_list.html (catalog/book_list.html in this case) inside the application's /application_name/templates/ directory (/catalog/templates/).

-
- -

您可以添加屬性,以更改上面的某種行為。例如,如果需要使用同一模型的多個視圖,則可以指定另一個模板文件,或者如果book_list對於特定模板用例不直觀,則可能需要使用不同的模板變量名稱。可能最有用的變更,是更改/過濾返回的結果子集-因此,您可能會列出其他用戶閱讀的前5本書,而不是列出所有書本。

- -
class BookListView(generic.ListView):
-    model = Book
-    context_object_name = 'my_book_list'   # your own name for the list as a template variable
-    queryset = Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war
-    template_name = 'books/my_arbitrary_template_name_list.html'  # Specify your own template name/location
- -

Overriding methods in class-based views

- -

雖然我們不需要在這裡執行此操作,但您也可以覆寫某些類別方法。

- -

例如,我們可以覆寫get_queryset()方法,來更改返回的記錄列表。這比單獨設置queryset屬性更靈活,就像我們在前面的代碼片段中進行的那樣(儘管在這案例中沒有太大用處):

- -
class BookListView(generic.ListView):
-    model = Book
-
-    def get_queryset(self):
-        return Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war
-
- -

我們還可以重寫get_context_data() 以便將其他上下文變數傳遞給模組 (例如,默認情況下傳遞書籍列表). 下面的片段顯示瞭如何向上下文添加名為"some_data" 的變數(然後它將用作模組變數)

- -
class BookListView(generic.ListView):
-    model = Book
-
-    def get_context_data(self, **kwargs):
-        # Call the base implementation first to get the context
-        context = super(BookListView, self).get_context_data(**kwargs)
-        # Create any data and add it to the context
-        context['some_data'] = 'This is just some data'
-        return context
- -

執行此操作時,務必遵循上面使用的模式:

- -
    -
  • 首先從我們的superclass中獲取現有內文。
  • -
  • 然後添加新的內文信息。
  • -
  • 然後返回新的(更新後)內文。
  • -
- -
-

Note: Check out Built-in class-based generic views (Django docs) for many more examples of what you can do.

-
- -

Creating the List View template

- -

建立HTML及複製以下文字串到/locallibrary/catalog/templates/catalog/book_list.html , 這是基於通用類的列表視圖所期望的默認模板文件 (默認在catalog中名稱為Book 的模組).

- -

通用的views模板跟其他的模板沒有不同 (儘管傳遞給模板的內文/訊息當然可以不同). 與index模板一樣,我們在第一行中擴展了基本模板,然後更替名為 content的區塊。

- -
{% extends "base_generic.html" %}
-
-{% block content %}
-  <h1>Book List</h1>
-  {% if book_list %}
-  <ul>
-    {% for book in book_list %}
-      <li>
-        <a href="\{{ book.get_absolute_url }}">\{{ book.title }}</a> (\{{book.author}})
-      </li>
-    {% endfor %}
-  </ul>
-  {% else %}
-    <p>There are no books in the library.</p>
-  {% endif %} 
-{% endblock %}
- -

該視圖默認將上下文(書籍列表)作為object_listbook_list 別名傳遞;兩者都會起作用.

- -

Conditional execution

- -

我們使用 if, elseendif 模組標籤,以檢查book_list 是否已定義並且不為空。 如果 book_list 為空值, 則 else 子句回傳text 說明沒有書可以列出. 如果book_list不是空值, 然後我們遍曆書籍清單。

- -
{% if book_list %}
-  <!-- code here to list the books -->
-{% else %}
-  <p>There are no books in the library.</p>
-{% endif %}
-
- -

The condition above only checks for one case, but you can test on additional conditions using the elif template tag (e.g. {% elif var2 %} ). For more information about conditional operators see: if, ifequal/ifnotequal, and ifchanged in Built-in template tags and filters (Django Docs).

- -

For loops

- -

The template uses the for and endfor template tags to loop through the book list, as shown below. Each iteration populates the book template variable with information for the current list item.

- -
{% for book in book_list %}
-  <li> <!-- code here get information from each book item --> </li>
-{% endfor %}
-
- -

While not used here, within the loop Django will also create other variables that you can use to track the iteration. For example, you can test the forloop.last variable to perform conditional processing the last time that the loop is run.

- -

Accessing variables

- -

The code inside the loop creates a list item for each book that shows both the title (as a link to the yet-to-be-created detail view) and the author.

- -
<a href="\{{ book.get_absolute_url }}">\{{ book.title }}</a> (\{{book.author}})
-
- -

We access the fields of the associated book record using the "dot notation" (e.g. book.title and book.author), where the text following the book item is the field name (as defined in the model).

- -

We can also call functions in the model from within our template — in this case we call Book.get_absolute_url() to get an URL you could use to display the associated detail record. This works provided the function does not have any arguments (there is no way to pass arguments!)

- -
-

Note: We have to be a little careful of "side effects" when calling functions in templates. Here we just get a URL to display, but a function can do pretty much anything — we wouldn't want to delete our database (for example) just by rendering our template!

-
- -

Update the base template

- -

Open the base template (/locallibrary/catalog/templates/base_generic.html) and insert {% url 'books' %} into the URL link for All books, as shown below. This will enable the link in all pages (we can successfully put this in place now that we've created the "books" url mapper).

- -
<li><a href="{% url 'index' %}">Home</a></li>
-<li><a href="{% url 'books' %}">All books</a></li>
-<li><a href="">All authors</a></li>
- -

What does it look like?

- -

You won't be able to build book list yet, because we're still missing a dependency — the URL map for the book detail pages, which is needed to create hyperlinks to individual books. We'll show both list and detail views after the next section.

- -

Book detail page

- -

The book detail page will display information about a specific book, accessed using the URL catalog/book/<id> (where <id> is the primary key for the book). In addition to fields in the Book model (author, summary, ISBN, language, and genre), we'll also list the details of the available copies (BookInstances) including the status, expected return date, imprint, and id. This will allow our readers not just to learn about the book, but also to confirm whether/when it is available.

- -

URL mapping

- -

Open /catalog/urls.py and add the 'book-detail' URL mapper shown in bold below. This path() function defines a pattern, associated generic class-based detail view, and a name.

- -
urlpatterns = [
-    path('', views.index, name='index'),
-    path('books/', views.BookListView.as_view(), name='books'),
-    path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),
-]
- -

For the book-detail path the URL pattern uses a special syntax to capture the specific id of the book that we want to see. The syntax is very simple: angle brackets define the part of the URL to be captured, enclosing the name of the variable that the view can use to access the captured data. For example, <something> , will capture the marked pattern and pass the value to the view as a variable "something". You can optionally precede the variable name with a converter specification that defines the type of data (int, str, slug, uuid, path).

- -

In this case we use '<int:pk>' to capture the book id, which must be an integer, and pass it to the view as a parameter named pk (short for primary key).

- -
-

Note: As discussed previously, our matched URL is actually catalog/book/<digits> (because we are in the catalog application, /catalog/ is assumed).

-
- -
-

Important: The generic class-based detail view expects to be passed a parameter named pk. If you're writing your own function view you can use whatever parameter name you like, or indeed pass the information in an unnamed argument.

-
- -

Advanced path matching/regular expression primer

- -
-

Note: You won't need this section to complete the tutorial! We provide it because knowing this option is likely to be useful in your Django-centric future.

-
- -

The pattern matching provided by path() is simple and useful for the (very common) cases where you just want to capture any string or integer. If you need more refined filtering (for example, to filter only strings that have a certain number of characters) then you can use the re_path() method.

- -

This method is used just like path() except that it allows you to specify a pattern using a Regular expression. For example, the previous path could have been written as shown below:

- -
re_path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'),
-
- -

Regular expressions are an incredibly powerful pattern mapping tool. They are, frankly, quite unintuitive and scary for beginners. Below is a very short primer!

- -

The first thing to know is that regular expressions should usually be declared using the raw string literal syntax (i.e. they are enclosed as shown: r'<your regular expression text goes here>').

- -

The main parts of the syntax you will need to know for declaring the pattern matches are:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SymbolMeaning
^Match the beginning of the text
$Match the end of the text
\dMatch a digit (0, 1, 2, ... 9)
\wMatch a word character, e.g. any upper- or lower-case character in the alphabet, digit or the underscore character (_)
+Match one or more of the preceding character. For example, to match one or more digits you would use \d+. To match one or more "a" characters, you could use a+
*Match zero or more of the preceding character. For example, to match nothing or a word you could use \w*
( )Capture the part of the pattern inside the brackets. Any captured values will be passed to the view as unnamed parameters (if multiple patterns are captured, the associated parameters will be supplied in the order that the captures were declared).
(?P<name>...)Capture the pattern (indicated by ...) as a named variable (in this case "name"). The captured values are passed to the view with the name specified. Your view must therefore declare an argument with the same name!
[ ]Match against one character in the set. For example, [abc] will match on 'a' or 'b' or 'c'. [-\w] will match on the '-' character or any word character.
- -

Most other characters can be taken literally!

- -

Lets consider a few real examples of patterns:

- - - - - - - - - - - - - - - - - - - - - - -
PatternDescription
r'^book/(?P<pk>\d+)$' -

This is the RE used in our url mapper. It matches a string that has book/ at the start of the line (^book/), then has one or more digits (\d+), and then ends (with no non-digit characters before the end of line marker).

- -

It also captures all the digits (?P<pk>\d+) and passes them to the view in a parameter named 'pk'. The captured values are always passed as a string!

- -

For example, this would match book/1234 , and send a variable pk='1234' to the view.

-
r'^book/(\d+)$'This matches the same URLs as the preceding case. The captured information would be sent as an unnamed argument to the view.
r'^book/(?P<stub>[-\w]+)$' -

This matches a string that has book/ at the start of the line (^book/), then has one or more characters that are either a '-' or a word character ([-\w]+), and then ends. It also captures this set of characters and passes them to the view in a parameter named 'stub'.

- -

This is a fairly typical pattern for a "stub". Stubs are URL-friendly word-based primary keys for data. You might use a stub if you wanted your book URL to be more informative. For example /catalog/book/the-secret-garden rather than /catalog/book/33.

-
- -

You can capture multiple patterns in the one match, and hence encode lots of different information in a URL.

- -
-

Note: As a challenge, consider how you might encode an url to list all books released in a particular year, month, day, and the RE that could be used to match it.

-
- -

Passing additional options in your URL maps

- -

One feature that we haven't used here, but which you may find valuable, is that you can declare and pass additional options to the view. The options are declared as a dictionary that you pass as the third un-named argument to the path() function. This approach can be useful if you want to use the same view for multiple resources, and pass data to configure its behaviour in each case (below we supply a different template in each case).

- -
path('url/', views.my_reused_view, {'my_template_name': 'some_path'}, name='aurl'),
-path('anotherurl/', views.my_reused_view, {'my_template_name': 'another_path'}, name='anotherurl'),
-
- -
-

Note: Both extra options and named captured patterns are passed to the view as named arguments. If you use the same name for both a captured pattern and an extra option then only the captured pattern value will be sent to the view (the value specified in the additional option will be dropped).

-
- -

View (class-based)

- -

Open catalog/views.py, and copy the following code into the bottom of the file:

- -
class BookDetailView(generic.DetailView):
-    model = Book
- -

That's it! All you need to do now is create a template called /locallibrary/catalog/templates/catalog/book_detail.html, and the view will pass it the database information for the specific Book record extracted by the URL mapper. Within the template you can access the list of books with the template variable named object OR book (i.e. generically "the_model_name").

- -

If you need to, you can change the template used and the name of the context object used to reference the book in the template. You can also override methods to, for example, add additional information to the context.

- -

What happens if the record doesn't exist?

- -

If a requested record does not exist then the generic class-based detail view will raise an Http404 exception for you automatically — in production this will automatically display an appropriate "resource not found" page, which you can customise if desired.

- -

Just to give you some idea of how this works, the code fragment below demonstrates how you would implement the class-based view as a function, if you were not using the generic class-based detail view.

- -
def book_detail_view(request, primary_key):
-    try:
-        book = Book.objects.get(pk=primary_key)
-    except Book.DoesNotExist:
-        raise Http404('Book does not exist')
-
-    # from django.shortcuts import get_object_or_404
-    # book = get_object_or_404(Book, pk=primary_key)
-
-    return render(request, 'catalog/book_detail.html', context={'book': book})
-
- -

The view first tries to get the specific book record from the model. If this fails the view should raise an Http404 exception to indicate that the book is "not found". The final step is then, as usual, to call render() with the template name and the book data in the context parameter (as a dictionary).

- -
-

Note: The get_object_or_404() (shown commented out above) is a convenient shortcut to raise an Http404 exception if the record is not found.

-
- -

Creating the Detail View template

- -

Create the HTML file /locallibrary/catalog/templates/catalog/book_detail.html and give it the below content. As discussed above, this is the default template file name expected by the generic class-based detail view (for a model named Book in an application named catalog).

- -
{% extends "base_generic.html" %}
-
-{% block content %}
-  <h1>Title: \{{ book.title }}</h1>
-
-  <p><strong>Author:</strong> <a href="">\{{ book.author }}</a></p> <!-- author detail link not yet defined -->
-  <p><strong>Summary:</strong> \{{ book.summary }}</p>
-  <p><strong>ISBN:</strong> \{{ book.isbn }}</p>
-  <p><strong>Language:</strong> \{{ book.language }}</p>
-  <p><strong>Genre:</strong> {% for genre in book.genre.all %} \{{ genre }}{% if not forloop.last %}, {% endif %}{% endfor %}</p>
-
-  <div style="margin-left:20px;margin-top:20px">
-    <h4>Copies</h4>
-
-    {% for copy in book.bookinstance_set.all %}
-    <hr>
-    <p class="{% if copy.status == 'a' %}text-success{% elif copy.status == 'm' %}text-danger{% else %}text-warning{% endif %}">\{{ copy.get_status_display }}</p>
-    {% if copy.status != 'a' %}<p><strong>Due to be returned:</strong> \{{copy.due_back}}</p>{% endif %}
-    <p><strong>Imprint:</strong> \{{copy.imprint}}</p>
-    <p class="text-muted"><strong>Id:</strong> \{{copy.id}}</p>
-    {% endfor %}
-  </div>
-{% endblock %}
- -
    -
- -
-

The author link in the template above has an empty URL because we've not yet created an author detail page. Once that exists, you should update the URL like this:

- -
<a href="{% url 'author-detail' book.author.pk %}">\{{ book.author }}</a>
-
-
- -

Though a little larger, almost everything in this template has been described previously:

- -
    -
  • We extend our base template and override the "content" block.
  • -
  • We use conditional processing to determine whether or not to display specific content.
  • -
  • We use for loops to loop through lists of objects.
  • -
  • We access the context fields using the dot notation (because we've used the detail generic view, the context is named book; we could also use "object")
  • -
- -

The one interesting thing we haven't seen before is the function book.bookinstance_set.all(). This method is "automagically" constructed by Django in order to return the set of BookInstance records associated with a particular Book.

- -
{% for copy in book.bookinstance_set.all %}
-<!-- code to iterate across each copy/instance of a book -->
-{% endfor %}
- -

需要這方法是因為我們僅在“一”那側model(Book)定義一個ForeignKey (一對多)字段的關聯,也因為沒有任何的關聯被定義在“多”那側model(BookInstance),故無法透過字段來取得相關的紀錄。為了克服這個問題,Django建立一個function取名為“reverse lookup”供使用。function的名字以一對多關係中該 ForeignKey 被定義在的那個模型名稱小寫,再在字尾加上_set(因此在 Book 創建的function名是 bookinstance_set())。

- -
-

Note: 在這我們使用 all() 取得所有紀錄 (預設),你無法直接在template做是因為你無法指定引數到function,但你可用 filter() 方法取得一個紀錄的子集 。

- -

順帶一提,若你不再基於類的view或model定義順序(order),開發伺服器會將會報錯類似的訊息:

- -
[29/May/2017 18:37:53] "GET /catalog/books/?page=1 HTTP/1.1" 200 1637
-/foo/local_library/venv/lib/python3.5/site-packages/django/views/generic/list.py:99: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <QuerySet [<Author: Ortiz, David>, <Author: H. McRaven, William>, <Author: Leigh, Melinda>]>
-  allow_empty_first_page=allow_empty_first_page, **kwargs)
-
- -

That happens because the paginator object expects to see some ORDER BY being executed on your underlying database. Without it, it can't be sure the records being returned are actually in the right order!

- -

This tutorial didn't reach Pagination (yet, but soon enough), but since you can't use sort_by() and pass a parameter (the same with filter() described above) you will have to choose between three choices:

- -
    -
  1. Add a ordering inside a class Meta declaration on your model.
  2. -
  3. Add a queryset attribute in your custom class-based view, specifying a order_by().
  4. -
  5. Adding a get_queryset method to your custom class-based view and also specify the order_by().
  6. -
- -

If you decide to go with a class Meta for the Author model (probably not as flexible as customizing the class-based view, but easy enough), you will end up with something like this:

- -
class Author(models.Model):
-    first_name = models.CharField(max_length=100)
-    last_name = models.CharField(max_length=100)
-    date_of_birth = models.DateField(null=True, blank=True)
-    date_of_death = models.DateField('Died', null=True, blank=True)
-
-    def get_absolute_url(self):
-        return reverse('author-detail', args=[str(self.id)])
-
-    def __str__(self):
-        return f'{self.last_name}, {self.first_name}'
-
-    class Meta:
-        ordering = ['last_name']
- -

Of course, the field doesn't need to be last_name: it could be any other.

- -

And last, but not least, you should sort by an attribute/column that actually has a index (unique or not) on your database to avoid performance issues. Of course, this will not be necessary here (and we are probably getting ourselves too much ahead) if such small amount of books (and users!), but it is something to keep in mind for future projects.

-
- -

What does it look like?

- -

At this point we should have created everything needed to display both the book list and book detail pages. Run the server (python3 manage.py runserver) and open your browser to http://127.0.0.1:8000/.

- -
-

Warning: Don't click any author or author detail links yet — you'll create those in the challenge!

-
- -

Click the All books link to display the list of books.

- -

Book List Page

- -

Then click a link to one of your books. If everything is set up correctly, you should see something like the following screenshot.

- -

Book Detail Page

- -

Pagination

- -

If you've just got a few records, our book list page will look fine. However, as you get into the tens or hundreds of records the page will take progressively longer to load (and have far too much content to browse sensibly). The solution to this problem is to add pagination to your list views, reducing the number of items displayed on each page.

- -

Django has excellent in-built support for pagination. Even better, this is built into the generic class-based list views so you don't have to do very much to enable it!

- -

Views

- -

Open catalog/views.py, and add the paginate_by line shown in bold below.

- -
class BookListView(generic.ListView):
-    model = Book
-    paginate_by = 10
- -

With this addition, as soon as you have more than 10 records the view will start paginating the data it sends to the template. The different pages are accessed using GET parameters — to access page 2 you would use the URL: /catalog/books/?page=2.

- -

Templates

- -

Now that the data is paginated, we need to add support to the template to scroll through the results set. Because we might want to do this in all list views, we'll do this in a way that can be added to the base template.

- -

Open /locallibrary/catalog/templates/base_generic.html and copy in the following pagination block below our content block (highlighted below in bold). The code first checks if pagination is enabled on the current page. If so then it adds next and previous links as appropriate (and the current page number).

- -
{% block content %}{% endblock %}
-
-{% block pagination %}
-  {% if is_paginated %}
-    <div class="pagination">
-      <span class="page-links">
-        {% if page_obj.has_previous %}
-          <a href="\{{ request.path }}?page=\{{ page_obj.previous_page_number }}">previous</a>
-        {% endif %}
-        <span class="page-current">
-          <p>Page \{{ page_obj.number }} of \{{ page_obj.paginator.num_pages }}.</p>
-        </span>
-        {% if page_obj.has_next %}
-          <a href="\{{ request.path }}?page=\{{ page_obj.next_page_number }}">next</a>
-        {% endif %}
-      </span>
-    </div>
-  {% endif %}
-{% endblock %} 
- -

The page_obj is a Paginator object that will exist if pagination is being used on the current page. It allows you to get all the information about the current page, previous pages, how many pages there are, etc.

- -

We use \{{ request.path }} to get the current page URL for creating the pagination links. This is useful, because it is independent of the object that we're paginating.

- -

Thats it!

- -

What does it look like?

- -

The screenshot below shows what the pagination looks like — if you haven't entered more than 10 titles into your database, then you can test it more easily by lowering the number specified in the paginate_by line in your catalog/views.py file. To get the below result we changed it to paginate_by = 2.

- -

The pagination links are displayed on the bottom, with next/previous links being displayed depending on which page you're on.

- -

Book List Page - paginated

- -

Challenge yourself

- -

The challenge in this article is to create the author detail and list views required to complete the project. These should be made available at the following URLs:

- -
    -
  • catalog/authors/ — The list of all authors.
  • -
  • catalog/author/<id> — The detail view for the specific author with a primary key field named <id>
  • -
- -

The code required for the URL mappers and the views should be virtually identical to the Book list and detail views we created above. The templates will be different, but will share similar behaviour.

- -
-

Note:

- -
    -
  • Once you've created the URL mapper for the author list page you will also need to update the All authors link in the base template. Follow the same process as we did when we updated the All books link.
  • -
  • Once you've created the URL mapper for the author detail page, you should also update the book detail view template (/locallibrary/catalog/templates/catalog/book_detail.html) so that the author link points to your new author detail page (rather than being an empty URL). The line will change to add the template tag shown in bold below. -
    <p><strong>Author:</strong> <a href="{% url 'author-detail' book.author.pk %}">\{{ book.author }}</a></p>
    -
    -
  • -
-
- -

When you are finished, your pages should look something like the screenshots below.

- -

Author List Page

- -
    -
- -

Author Detail Page

- -
    -
- -

Summary

- -

Congratulations, our basic library functionality is now complete!

- -

In this article we've learned how to use the generic class-based list and detail views and used them to create pages to view our books and authors. Along the way we've learned about pattern matching with regular expressions, and how you can pass data from URLs to your views. We've also learned a few more tricks for using templates. Last of all we've shown how to paginate list views, so that our lists are managable even when we have many records.

- -

In our next articles we'll extend this library to support user accounts, and thereby demonstrate user authentication, permissons, sessions, and forms.

- -

See also

- - - -

{{PreviousMenuNext("Learn/Server-side/Django/Home_page", "Learn/Server-side/Django/Sessions", "Learn/Server-side/Django")}}

- -

In this module

- - diff --git a/files/zh-tw/learn/server-side/django/generic_views/index.md b/files/zh-tw/learn/server-side/django/generic_views/index.md new file mode 100644 index 00000000000000..6bcb2c82e51a25 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/generic_views/index.md @@ -0,0 +1,588 @@ +--- +title: 'Django Tutorial Part 6: Generic list and detail views' +slug: Learn/Server-side/Django/Generic_views +translation_of: Learn/Server-side/Django/Generic_views +--- +{{LearnSidebar}}{{PreviousMenuNext("Learn/Server-side/Django/Home_page", "Learn/Server-side/Django/Sessions", "Learn/Server-side/Django")}} + +本教程擴充了 [LocalLibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) 網站,為書本與作者增加列表與細節頁面。此處我們將學到通用類別視圖,並演示如何降低你必須為一般使用案例撰寫的程式碼數量。我們也會更加深入 URL 處理細節,演示如何實施基本模式匹配。 + + + + + + + + + + + + +
前提: + Complete all previous tutorial topics, including + Django Tutorial Part 5: Creating our home page. +
目的: + To understand where and how to use generic class-based views, and how to + extract patterns from URLs and pass the information to views. +
+ +## Overview + +本教程中,通過為書本和作者添加列表和詳細信息頁面,我們將完成第一個版本的 [LocalLibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) 網站(或者更準確地說,我們將向您展示如何實現書頁,並讓您自己創建作者頁面!) ) + +該過程在創建索引頁面,我們在上一個教程中展示了該頁面。我們仍然需要創建 URL 地圖,視圖和模板。主要區別在於,對於詳細信息頁面,我們還有一個額外的挑戰,即從 URL 對於這些頁面,我們將演示一種完全不同的視圖類型:基於類別的通用列表和詳細視圖。這些可以顯著減少所需的視圖代碼量,有助於更容易編寫和維護。 + +本教程的最後一部分,將演示在使用基於類別的通用列表視圖時,如何對數據進行分頁。 + +## Book list page + +該書將顯示每條記錄的標題和作者,標題是指向相關圖書詳細信息頁面的超鏈接。該頁面將具有與站點中,所有其他頁面相同的結構和導航,因此,我們可以擴展在上一個教程中創建的基本模板 (**base_generic.html**)。 + +### URL mapping + +開啟/catalog/urls.py,並複製加入下面粗體顯示的代碼。就像索引頁面的方式,這個 path()函數,定義了一個與 URL 匹配的模式('books /'),如果 URL 匹配,將調用視圖函數(views.BookListView\.as_view())和一個對應的特定映射的名稱。 + +```python +urlpatterns = [ + path('', views.index, name='index'), + path('books/', views.BookListView.as_view(), name='books'), +] +``` + +正如前一個教程中所討論的,URL 必須已經先匹配了/ catalog,因此實際上將為 URL 調用的視圖是:/ catalog / books /。 + +我們將繼承現有的泛型視圖函數,該函數已經完成了我們希望此視圖函數執行的大部分工作,而不是從頭開始編寫自己的函數。對於基於 Django 類的視圖,我們通過調用類方法 as_view(),來訪問適當的視圖函數。由此可以創建類的實例,並確保為 HTTP 請求正確的處理程序方法。 + +### View (class-based) + +我們可以很容易地,將書本列表列表編寫為常規函數(就像我們之前的索引視圖一樣),進入查詢數據庫中的所有書本,然後調用 render(),將列表傳遞給指定的模板。然而,我們用另一種方 ​​ 法取代,我們將使用基於類的通用列表視圖(ListView)-一個繼承自現有視圖的類。因為通用視圖,已經實現了我們需要的大部分功能,並且遵循 Django 最佳實踐,我們將能夠創建更強大的列表視圖,代碼更多,重複次數最多,最終維護所需。 + +開啟 catalog / views.py,將以下代碼複製到文件的底部: + +```python +from django.views import generic + +class BookListView(generic.ListView): + model = Book +``` + +就是這樣!通用 view 將查詢數據庫,以獲取指定模型(Book)的所有記錄,然後呈現/locallibrary/catalog/templates/catalog/book_list.html 的模板(我們將在下面創建)。在模板中,您可以使用所謂的 object_list 或 book_list 的模板變量(即通常為“ the_model_name_list”),以訪問書本列表。 + +> **備註:** This awkward path for the template location isn't a misprint — the generic views look for templates in `/application_name/the_model_name_list.html` (`catalog/book_list.html` in this case) inside the application's `/application_name/templates/` directory (`/catalog/templates/)`. + +您可以添加屬性,以更改上面的某種行為。例如,如果需要使用同一模型的多個視圖,則可以指定另一個模板文件,或者如果 book_list 對於特定模板用例不直觀,則可能需要使用不同的模板變量名稱。可能最有用的變更,是更改/過濾返回的結果子集-因此,您可能會列出其他用戶閱讀的前 5 本書,而不是列出所有書本。 + +```python +class BookListView(generic.ListView): + model = Book + context_object_name = 'my_book_list' # your own name for the list as a template variable + queryset = Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war + template_name = 'books/my_arbitrary_template_name_list.html' # Specify your own template name/location +``` + +#### Overriding methods in class-based views + +雖然我們不需要在這裡執行此操作,但您也可以覆寫某些類別方法。 + +例如,我們可以覆寫 get_queryset()方法,來更改返回的記錄列表。這比單獨設置 queryset 屬性更靈活,就像我們在前面的代碼片段中進行的那樣(儘管在這案例中沒有太大用處): + +```python +class BookListView(generic.ListView): + model = Book + + def get_queryset(self): + return Book.objects.filter(title__icontains='war')[:5] # Get 5 books containing the title war +``` + +我們還可以重寫`get_context_data()` 以便將其他上下文變數傳遞給模組 (例如,默認情況下傳遞書籍列表). 下面的片段顯示瞭如何向上下文添加名為"`some_data`" 的變數(然後它將用作模組變數) + +```python +class BookListView(generic.ListView): + model = Book + + def get_context_data(self, **kwargs): + # Call the base implementation first to get the context + context = super(BookListView, self).get_context_data(**kwargs) + # Create any data and add it to the context + context['some_data'] = 'This is just some data' + return context +``` + +執行此操作時,務必遵循上面使用的模式: + +- 首先從我們的 superclass 中獲取現有內文。 +- 然後添加新的內文信息。 +- 然後返回新的(更新後)內文。 + +> **備註:** Check out [Built-in class-based generic views](https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-display/) (Django docs) for many more examples of what you can do. + +### Creating the List View template + +建立 HTML 及複製以下文字串到**/locallibrary/catalog/templates/catalog/book_list.html** , 這是基於通用類的列表視圖所期望的默認模板文件 (默認在`catalog中名稱為Book` 的模組). + +通用的 views 模板跟其他的模板沒有不同 (儘管傳遞給模板的內文/訊息當然可以不同). 與 index 模板一樣,我們在第一行中擴展了基本模板,然後更替名為 `content`的區塊。 + +```html +{% extends "base_generic.html" %} + +{% block content %} +

Book List

+ {% if book_list %} +
    + {% for book in book_list %} +
  • + \{{ book.title }} (\{{book.author}}) +
  • + {% endfor %} +
+ {% else %} +

There are no books in the library.

+ {% endif %} +{% endblock %} +``` + +該視圖默認將上下文(書籍列表)作為`object_list` 和 `book_list` 別名傳遞;兩者都會起作用. + +#### Conditional execution + +我們使用 [`if`](https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#if), `else` 和 `endif` 模組標籤,以檢查`book_list` 是否已定義並且不為空。 如果 `book_list` 為空值, 則 `else` 子句回傳 text 說明沒有書可以列出. 如果`book_list`不是空值, 然後我們遍曆書籍清單。 + +```html +{% if book_list %} + +{% else %} +

There are no books in the library.

+{% endif %} +``` + +The condition above only checks for one case, but you can test on additional conditions using the `elif` template tag (e.g. `{% elif var2 %}` ). For more information about conditional operators see: [if](https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#if), [ifequal/ifnotequal](https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#ifequal-and-ifnotequal), and [ifchanged](https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#ifchanged) in [Built-in template tags and filters](https://docs.djangoproject.com/en/2.0/ref/templates/builtins) (Django Docs). + +#### For loops + +The template uses the [for](https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#for) and `endfor` template tags to loop through the book list, as shown below. Each iteration populates the `book` template variable with information for the current list item. + +```html +{% for book in book_list %} +
  • +{% endfor %} +``` + +While not used here, within the loop Django will also create other variables that you can use to track the iteration. For example, you can test the `forloop.last` variable to perform conditional processing the last time that the loop is run. + +#### Accessing variables + +The code inside the loop creates a list item for each book that shows both the title (as a link to the yet-to-be-created detail view) and the author. + +```html +\{{ book.title }} (\{{book.author}}) +``` + +We access the _fields_ of the associated book record using the "dot notation" (e.g. `book.title` and `book.author`), where the text following the `book` item is the field name (as defined in the model). + +We can also call _functions_ in the model from within our template — in this case we call `Book.get_absolute_url()` to get an URL you could use to display the associated detail record. This works provided the function does not have any arguments (there is no way to pass arguments!) + +> **備註:** We have to be a little careful of "side effects" when calling functions in templates. Here we just get a URL to display, but a function can do pretty much anything — we wouldn't want to delete our database (for example) just by rendering our template! + +#### Update the base template + +Open the base template (**/locallibrary/catalog/templates/_base_generic.html_**) and insert **{% url 'books' %}** into the URL link for **All books**, as shown below. This will enable the link in all pages (we can successfully put this in place now that we've created the "books" url mapper). + +```python +
  • Home
  • +
  • All books
  • +
  • All authors
  • +``` + +### What does it look like? + +You won't be able to build book list yet, because we're still missing a dependency — the URL map for the book detail pages, which is needed to create hyperlinks to individual books. We'll show both list and detail views after the next section. + +## Book detail page + +The book detail page will display information about a specific book, accessed using the URL `catalog/book/` (where `` is the primary key for the book). In addition to fields in the `Book` model (author, summary, ISBN, language, and genre), we'll also list the details of the available copies (`BookInstances`) including the status, expected return date, imprint, and id. This will allow our readers not just to learn about the book, but also to confirm whether/when it is available. + +### URL mapping + +Open **/catalog/urls.py** and add the '**book-detail**' URL mapper shown in bold below. This `path()` function defines a pattern, associated generic class-based detail view, and a name. + +```python +urlpatterns = [ + path('', views.index, name='index'), + path('books/', views.BookListView.as_view(), name='books'), + path('book/', views.BookDetailView.as_view(), name='book-detail'), +] +``` + +For the _book-detail_ path the URL pattern uses a special syntax to capture the specific id of the book that we want to see. The syntax is very simple: angle brackets define the part of the URL to be captured, enclosing the name of the variable that the view can use to access the captured data. For example, **\** , will capture the marked pattern and pass the value to the view as a variable "something". You can optionally precede the variable name with a [converter specification](https://docs.djangoproject.com/en/2.0/topics/http/urls/#path-converters) that defines the type of data (int, str, slug, uuid, path). + +In this case we use `''` to capture the book id, which must be an integer, and pass it to the view as a parameter named `pk` (short for primary key). + +> **備註:** As discussed previously, our matched URL is actually `catalog/book/` (because we are in the **catalog** application, `/catalog/` is assumed). + +> **警告:** The generic class-based detail view _expects_ to be passed a parameter named **pk**. If you're writing your own function view you can use whatever parameter name you like, or indeed pass the information in an unnamed argument. + +#### Advanced path matching/regular expression primer + +> **備註:** You won't need this section to complete the tutorial! We provide it because knowing this option is likely to be useful in your Django-centric future. + +The pattern matching provided by `path()` is simple and useful for the (very common) cases where you just want to capture _any_ string or integer. If you need more refined filtering (for example, to filter only strings that have a certain number of characters) then you can use the [re_path()](https://docs.djangoproject.com/en/2.0/ref/urls/#django.urls.re_path) method. + +This method is used just like `path()` except that it allows you to specify a pattern using a [Regular expression](https://docs.python.org/3/library/re.html). For example, the previous path could have been written as shown below: + +```python +re_path(r'^book/(?P\d+)$', views.BookDetailView.as_view(), name='book-detail'), +``` + +_Regular expressions_ are an incredibly powerful pattern mapping tool. They are, frankly, quite unintuitive and scary for beginners. Below is a very short primer! + +The first thing to know is that regular expressions should usually be declared using the raw string literal syntax (i.e. they are enclosed as shown: **r'\'**). + +The main parts of the syntax you will need to know for declaring the pattern matches are: + +| Symbol | Meaning | +| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ^ | Match the beginning of the text | +| $ | Match the end of the text | +| \d | Match a digit (0, 1, 2, ... 9) | +| \w | Match a word character, e.g. any upper- or lower-case character in the alphabet, digit or the underscore character (\_) | +| + | Match one or more of the preceding character. For example, to match one or more digits you would use `\d+`. To match one or more "a" characters, you could use `a+` | +| \* | Match zero or more of the preceding character. For example, to match nothing or a word you could use `\w*` | +| ( ) | Capture the part of the pattern inside the brackets. Any captured values will be passed to the view as unnamed parameters (if multiple patterns are captured, the associated parameters will be supplied in the order that the captures were declared). | +| (?P<_name_>...) | Capture the pattern (indicated by ...) as a named variable (in this case "name"). The captured values are passed to the view with the name specified. Your view must therefore declare an argument with the same name! | +| [ ] | Match against one character in the set. For example, [abc] will match on 'a' or 'b' or 'c'. [-\w] will match on the '-' character or any word character. | + +Most other characters can be taken literally! + +Lets consider a few real examples of patterns: + + + + + + + + + + + + + + + + + + + + + + +
    PatternDescription
    r'^book/(?P<pk>\d+)$' +

    + This is the RE used in our url mapper. It matches a string that has + book/ at the start of the line (^book/), + then has one or more digits (\d+), and then ends (with no + non-digit characters before the end of line marker). +

    +

    + It also captures all the digits (?P<pk>\d+) and + passes them to the view in a parameter named 'pk'. + The captured values are always passed as a string! +

    +

    + For example, this would match book/1234 , and send a + variable pk='1234' to the view. +

    +
    r'^book/(\d+)$' + This matches the same URLs as the preceding case. The captured + information would be sent as an unnamed argument to the view. +
    r'^book/(?P<stub>[-\w]+)$' +

    + This matches a string that has book/ at the start of the + line (^book/), then has one or more characters that + are either a '-' or a word character + ([-\w]+), and then ends. It also captures this set of + characters and passes them to the view in a parameter named 'stub'. +

    +

    + This is a fairly typical pattern for a "stub". Stubs are URL-friendly + word-based primary keys for data. You might use a stub if you wanted + your book URL to be more informative. For example + /catalog/book/the-secret-garden rather than + /catalog/book/33. +

    +
    + +You can capture multiple patterns in the one match, and hence encode lots of different information in a URL. + +> **備註:** As a challenge, consider how you might encode an url to list all books released in a particular year, month, day, and the RE that could be used to match it. + +#### Passing additional options in your URL maps + +One feature that we haven't used here, but which you may find valuable, is that you can declare and pass [additional options](https://docs.djangoproject.com/en/2.0/topics/http/urls/#views-extra-options) to the view. The options are declared as a dictionary that you pass as the third un-named argument to the `path()` function. This approach can be useful if you want to use the same view for multiple resources, and pass data to configure its behaviour in each case (below we supply a different template in each case). + +```python +path('url/', views.my_reused_view, {'my_template_name': 'some_path'}, name='aurl'), +path('anotherurl/', views.my_reused_view, {'my_template_name': 'another_path'}, name='anotherurl'), +``` + +> **備註:** Both extra options and named captured patterns are passed to the view as _named_ arguments. If you use the **same name** for both a captured pattern and an extra option then only the captured pattern value will be sent to the view (the value specified in the additional option will be dropped). + +### View (class-based) + +Open **catalog/views.py**, and copy the following code into the bottom of the file: + +```python +class BookDetailView(generic.DetailView): + model = Book +``` + +That's it! All you need to do now is create a template called **/locallibrary/catalog/templates/catalog/book_detail.html**, and the view will pass it the database information for the specific `Book` record extracted by the URL mapper. Within the template you can access the list of books with the template variable named `object` OR `book` (i.e. generically "`the_model_name`"). + +If you need to, you can change the template used and the name of the context object used to reference the book in the template. You can also override methods to, for example, add additional information to the context. + +#### What happens if the record doesn't exist? + +If a requested record does not exist then the generic class-based detail view will raise an `Http404` exception for you automatically — in production this will automatically display an appropriate "resource not found" page, which you can customise if desired. + +Just to give you some idea of how this works, the code fragment below demonstrates how you would implement the class-based view as a function, if you were **not** using the generic class-based detail view. + +```python +def book_detail_view(request, primary_key): + try: + book = Book.objects.get(pk=primary_key) + except Book.DoesNotExist: + raise Http404('Book does not exist') + + # from django.shortcuts import get_object_or_404 + # book = get_object_or_404(Book, pk=primary_key) + + return render(request, 'catalog/book_detail.html', context={'book': book}) +``` + +The view first tries to get the specific book record from the model. If this fails the view should raise an `Http404` exception to indicate that the book is "not found". The final step is then, as usual, to call `render()` with the template name and the book data in the `context` parameter (as a dictionary). + +> **備註:** The `get_object_or_404()` (shown commented out above) is a convenient shortcut to raise an `Http404` exception if the record is not found. + +### Creating the Detail View template + +Create the HTML file **/locallibrary/catalog/templates/catalog/book_detail.html** and give it the below content. As discussed above, this is the default template file name expected by the generic class-based _detail_ view (for a model named `Book` in an application named `catalog`). + +```html +{% extends "base_generic.html" %} + +{% block content %} +

    Title: \{{ book.title }}

    + +

    Author: \{{ book.author }}

    +

    Summary: \{{ book.summary }}

    +

    ISBN: \{{ book.isbn }}

    +

    Language: \{{ book.language }}

    +

    Genre: {% for genre in book.genre.all %} \{{ genre }}{% if not forloop.last %}, {% endif %}{% endfor %}

    + +
    +

    Copies

    + + {% for copy in book.bookinstance_set.all %} +
    +

    \{{ copy.get_status_display }}

    + {% if copy.status != 'a' %}

    Due to be returned: \{{copy.due_back}}

    {% endif %} +

    Imprint: \{{copy.imprint}}

    +

    Id: \{{copy.id}}

    + {% endfor %} +
    +{% endblock %} +``` + +> **備註:** The author link in the template above has an empty URL because we've not yet created an author detail page. Once that exists, you should update the URL like this: +> +> \{{ book.author }} + +Though a little larger, almost everything in this template has been described previously: + +- We extend our base template and override the "content" block. +- We use conditional processing to determine whether or not to display specific content. +- We use `for` loops to loop through lists of objects. +- We access the context fields using the dot notation (because we've used the detail generic view, the context is named `book`; we could also use "`object`") + +The one interesting thing we haven't seen before is the function `book.bookinstance_set.all()`. This method is "automagically" constructed by Django in order to return the set of `BookInstance` records associated with a particular `Book`. + +```python +{% for copy in book.bookinstance_set.all %} + +{% endfor %} +``` + +需要這方法是因為我們僅在“一”那側 model(Book)定義一個`ForeignKey` (一對多)字段的關聯,也因為沒有任何的關聯被定義在“多”那側 model(BookInstance),故無法透過字段來取得相關的紀錄。為了克服這個問題,Django 建立一個 function 取名為“reverse lookup”供使用。function 的名字以一對多關係中該 `ForeignKey` 被定義在的那個模型名稱小寫,再在字尾加上`_set`(因此在 `Book` 創建的 function 名是 `bookinstance_set()`)。 + +> **備註:** 在這我們使用 `all()` 取得所有紀錄 (預設),你無法直接在 template 做是因為你無法指定引數到 function,但你可用 `filter()` 方法取得一個紀錄的子集 。 +> +> 順帶一提,若你不再基於類的 view 或 model 定義順序(order),開發伺服器會將會報錯類似的訊息: +> +> [29/May/2017 18:37:53] "GET /catalog/books/?page=1 HTTP/1.1" 200 1637 +> /foo/local_library/venv/lib/python3.5/site-packages/django/views/generic/list.py:99: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: , , ]> +> allow_empty_first_page=allow_empty_first_page, **kwargs) +> +> That happens because the [paginator object](https://docs.djangoproject.com/en/2.0/topics/pagination/#paginator-objects) expects to see some ORDER BY being executed on your underlying database. Without it, it can't be sure the records being returned are actually in the right order! +> +> This tutorial didn't reach **Pagination** (yet, but soon enough), but since you can't use `sort_by()` and pass a parameter (the same with `filter()` described above) you will have to choose between three choices: +> +> 1. Add a `ordering` inside a `class Meta` declaration on your model. +> 2. Add a `queryset` attribute in your custom class-based view, specifying a `order_by()`. +> 3. Adding a `get_queryset` method to your custom class-based view and also specify the `order_by()`. +> +> If you decide to go with a `class Meta` for the `Author` model (probably not as flexible as customizing the class-based view, but easy enough), you will end up with something like this: +> +> class Author(models.Model): +> first_name = models.CharField(max_length=100) +> last_name = models.CharField(max_length=100) +> date_of_birth = models.DateField(null=True, blank=True) +> date_of_death = models.DateField('Died', null=True, blank=True) +> +> def get_absolute_url(self): +> return reverse('author-detail', args=[str(self.id)]) +> +> def __str__(self): +> return f'{self.last_name}, {self.first_name}' +> +> class Meta: +> ordering = ['last_name'] +> +> Of course, the field doesn't need to be `last_name`: it could be any other. +> +> And last, but not least, you should sort by an attribute/column that actually has a index (unique or not) on your database to avoid performance issues. Of course, this will not be necessary here (and we are probably getting ourselves too much ahead) if such small amount of books (and users!), but it is something to keep in mind for future projects. + +## What does it look like? + +At this point we should have created everything needed to display both the book list and book detail pages. Run the server (`python3 manage.py runserver`) and open your browser to . + +> **警告:** Don't click any author or author detail links yet — you'll create those in the challenge! + +Click the **All books** link to display the list of books. + +![Book List Page](book_list_page_no_pagination.png) + +Then click a link to one of your books. If everything is set up correctly, you should see something like the following screenshot. + +![Book Detail Page](book_detail_page_no_pagination.png) + +## Pagination + +If you've just got a few records, our book list page will look fine. However, as you get into the tens or hundreds of records the page will take progressively longer to load (and have far too much content to browse sensibly). The solution to this problem is to add pagination to your list views, reducing the number of items displayed on each page. + +Django has excellent in-built support for pagination. Even better, this is built into the generic class-based list views so you don't have to do very much to enable it! + +### Views + +Open **catalog/views.py**, and add the `paginate_by` line shown in bold below. + +```python +class BookListView(generic.ListView): + model = Book + paginate_by = 10 +``` + +With this addition, as soon as you have more than 10 records the view will start paginating the data it sends to the template. The different pages are accessed using GET parameters — to access page 2 you would use the URL: `/catalog/books/?page=2`. + +### Templates + +Now that the data is paginated, we need to add support to the template to scroll through the results set. Because we might want to do this in all list views, we'll do this in a way that can be added to the base template. + +Open **/locallibrary/catalog/templates/_base_generic.html_** and copy in the following pagination block below our content block (highlighted below in bold). The code first checks if pagination is enabled on the current page. If so then it adds next and previous links as appropriate (and the current page number). + +```python +{% block content %}{% endblock %} + +{% block pagination %} + {% if is_paginated %} + + {% endif %} +{% endblock %} +``` + +The `page_obj` is a [Paginator](https://docs.djangoproject.com/en/2.0/topics/pagination/#paginator-objects) object that will exist if pagination is being used on the current page. It allows you to get all the information about the current page, previous pages, how many pages there are, etc. + +We use `\{{ request.path }}` to get the current page URL for creating the pagination links. This is useful, because it is independent of the object that we're paginating. + +Thats it! + +### What does it look like? + +The screenshot below shows what the pagination looks like — if you haven't entered more than 10 titles into your database, then you can test it more easily by lowering the number specified in the `paginate_by` line in your **catalog/views.py** file. To get the below result we changed it to `paginate_by = 2`. + +The pagination links are displayed on the bottom, with next/previous links being displayed depending on which page you're on. + +![Book List Page - paginated](book_list_paginated.png) + +## Challenge yourself + +The challenge in this article is to create the author detail and list views required to complete the project. These should be made available at the following URLs: + +- `catalog/authors/` — The list of all authors. +- `catalog/author/` — The detail view for the specific author with a primary key field named `` + +The code required for the URL mappers and the views should be virtually identical to the `Book` list and detail views we created above. The templates will be different, but will share similar behaviour. + +> **備註:** +> +> - Once you've created the URL mapper for the author list page you will also need to update the **All authors** link in the base template. Follow the [same process](#Update_the_base_template) as we did when we updated the **All books** link. +> - Once you've created the URL mapper for the author detail page, you should also update the [book detail view template](#Creating_the_Detail_View_template) (**/locallibrary/catalog/templates/catalog/book_detail.html**) so that the author link points to your new author detail page (rather than being an empty URL). The line will change to add the template tag shown in bold below. +> +> ```html +>

    Author: \{{ book.author }}

    +> ``` + +When you are finished, your pages should look something like the screenshots below. + +![Author List Page](author_list_page_no_pagination.png) + +![Author Detail Page](author_detail_page_no_pagination.png) + +## Summary + +Congratulations, our basic library functionality is now complete! + +In this article we've learned how to use the generic class-based list and detail views and used them to create pages to view our books and authors. Along the way we've learned about pattern matching with regular expressions, and how you can pass data from URLs to your views. We've also learned a few more tricks for using templates. Last of all we've shown how to paginate list views, so that our lists are managable even when we have many records. + +In our next articles we'll extend this library to support user accounts, and thereby demonstrate user authentication, permissons, sessions, and forms. + +## See also + +- [Built-in class-based generic views](https://docs.djangoproject.com/en/2.0/topics/class-based-views/generic-display/) (Django docs) +- [Generic display views](https://docs.djangoproject.com/en/2.0/ref/class-based-views/generic-display/) (Django docs) +- [Introduction to class-based views](https://docs.djangoproject.com/en/2.0/topics/class-based-views/intro/) (Django docs) +- [Built-in template tags and filters](https://docs.djangoproject.com/en/2.0/ref/templates/builtins) (Django docs). +- [Pagination](https://docs.djangoproject.com/en/2.0/topics/pagination/) (Django docs) + +{{PreviousMenuNext("Learn/Server-side/Django/Home_page", "Learn/Server-side/Django/Sessions", "Learn/Server-side/Django")}} + +## In this module + +- [Django introduction](/en-US/docs/Learn/Server-side/Django/Introduction) +- [Setting up a Django development environment](/en-US/docs/Learn/Server-side/Django/development_environment) +- [Django Tutorial: The Local Library website](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django Tutorial Part 2: Creating a skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) +- [Django Tutorial Part 3: Using models](/en-US/docs/Learn/Server-side/Django/Models) +- [Django Tutorial Part 4: Django admin site](/en-US/docs/Learn/Server-side/Django/Admin_site) +- [Django Tutorial Part 5: Creating our home page](/en-US/docs/Learn/Server-side/Django/Home_page) +- [Django Tutorial Part 6: Generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views) +- [Django Tutorial Part 7: Sessions framework](/en-US/docs/Learn/Server-side/Django/Sessions) +- [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/Authentication) +- [Django Tutorial Part 9: Working with forms](/en-US/docs/Learn/Server-side/Django/Forms) +- [Django Tutorial Part 10: Testing a Django web application](/en-US/docs/Learn/Server-side/Django/Testing) +- [Django Tutorial Part 11: Deploying Django to production](/en-US/docs/Learn/Server-side/Django/Deployment) +- [Django web application security](/en-US/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django mini blog](/en-US/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/home_page/index.html b/files/zh-tw/learn/server-side/django/home_page/index.html deleted file mode 100644 index 5ef1a7831bc9d1..00000000000000 --- a/files/zh-tw/learn/server-side/django/home_page/index.html +++ /dev/null @@ -1,383 +0,0 @@ ---- -title: 'Django Tutorial Part 5: Creating our home page' -slug: Learn/Server-side/Django/Home_page -translation_of: Learn/Server-side/Django/Home_page ---- -
    {{LearnSidebar}}
    - -
    {{PreviousMenuNext("Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django")}}
    - -

    我們現在可以添加代碼,來顯示我們的第一個完整頁面 - LocalLibrary 網站的主頁,顯示每個模型類型有多少條記錄,並提供我們其他頁面的側邊欄導航鏈接。一路上,我們將獲得編寫基本URL 地圖和視圖、從數據庫獲取記錄、以及使用模板的實踐經驗。

    - - - - - - - - - - - - -
    前提:讀 the Django Introduction. 完成上章節 (including Django Tutorial Part 4: Django admin site).
    目的:了解如何創建簡單的URL映射和視圖(沒有數據編碼在URL中)以及如何從模型中獲取數據並創建模版。
    - 概要
    - -

    總覽

    - -

    在定義了模型並創建了一些可以使用的初始庫記錄之後,是時候編寫將這些信息呈現給用戶的代碼了。 我們要做的第一件事是確定我們要在頁面中顯示的信息,並定義用於返回這些資源的URL。 然後,我們將創建一個URL映射器,視圖和模板來顯示頁面。

    - -

    下圖描述了主要數據流,以及處理HTTP請求和響應時所需的組件。 當我們已經實現了模型時,我們將創建的主要組件是:

    - -
      -
    • URL映射器將支持的URL(以及URL中編碼的任何信息)轉發到適當的視圖功能。
    • -
    • 查看函數可從模型中獲取所需的數據,創建顯示數據的HTML頁面,並將頁面返回給用戶以在瀏覽器中查看。
    • -
    • 在視圖中呈現數據時要使用的模板。
    • -
    - -

    - -

    正如您將在下一節中看到的那樣,我們將顯示5頁,這是太多信息,無法在一篇文章中進行記錄。 因此,本文將重點介紹如何實現主頁,我們將在後續文章中介紹其他頁面。 這應該使您對URL映射器,視圖和模型在實踐中如何工作有很好的端到端理解。

    - -

    定義資源URL

    - -

    由於此版本的LocalLibrary對於最終用戶基本上是只讀的,因此我們只需要提供該網站的登錄頁面(主頁),以及顯示書籍和作者的列表和詳細視圖的頁面。

    - -

    我們頁面所需的URL是:

    - -
      -
    • catalog/ — 主頁/索引頁面。
    • -
    • catalog/books/ — 所有書籍的清單。
    • -
    • catalog/authors/ — 所有作者列表。
    • -
    • catalog/book/<id> — 特定書的詳細信息視圖,其主鍵為 <id> (the default)。 因此,例如/catalog/book/3,作為添加的第三本書。
    • -
    • catalog/author/<id> — 特定作者的詳細信息視圖,其主鍵字段名為<id>。 例如,為第11位作者添加了/catalog/author/11
    • -
    - -

    前三個URL用於列出索引,書籍和作者。 它們不對任何其他信息進行編碼,並且雖然返回的結果將取決於數據庫中的內容,但為獲取信息而運行的查詢將始終相同。

    - -

    相比之下,最後兩個URL用於顯示有關特定書籍或作者的詳細信息-這些URL編碼要顯示在URL中的項目的標識(如上顯示為<id>)。 URL映射器可以提取編碼信息並將其傳遞給視圖,然後將動態確定從數據庫中獲取哪些信息。 通過在我們的URL中編碼信息,我們只需要一個URL映射,視圖和模板即可處理每本書(或作者)。

    - -
    -

    注意: Django允許您以自己喜歡的任何方式來構造URL-您可以如上所示在URL主體中編碼信息或使用URL GET 參數(例如/book/?id=6)。 無論使用哪種方法,都應保持URL的整潔,邏輯和可讀性(在此處查看W3C建議).

    - -

    Django文檔傾向於建議在URL正文中編碼信息,他們認為這種做法鼓勵更好的URL設計。

    -
    - -

    如概述中所述,本文的其餘部分描述瞭如何構造索引頁。

    - -

    創建索引頁面

    - -

    我們將創建的第一頁是索引頁 (catalog/)。 這將顯示一些靜態HTML,以及數據庫中不同記錄的一些計算出的“計數”。 為了完成這項工作,我們必須創建一個URL映射,視圖和模板。

    - -
    -

    注意:值得在本節中多加註意。 大多數材料是所有頁面共有的。

    -
    - -

    URL mapping

    - -

    創建skeleton website 時,我們更新了locallibrary/urls.py文件,以確保每當收到以 catalog/ 開頭的URL時, URLConf 模組 catalog.urls 都將處理其餘的子字符串。

    - -

    來自 locallibrary/urls.py的以下代碼片段包括catalog.urls 模塊:

    - -
    urlpatterns += [
    -    path('catalog/', include('catalog.urls')),
    -]
    -
    - -
    -

    注意: 每當Django遇到導入函數 django.urls.include()時,它都會在指定的結束字符處分割URL字符串,並將剩餘的子字符串發送到所包含的URLconf 模塊以進行進一步處理。

    -
    - -

    我們還為URLConf 模塊創建了一個佔位符文件,名為 /catalog/urls.py。 將以下行添加到該文件:

    - -
    urlpatterns = [
    -    path('', views.index, name='index'),
    -]
    - -

    path()函數定義以下內容:

    - -
      -
    • URL模式,它是一個空字符串:''。 處理其他視圖時,我們將詳細討論URL模式。
    • -
    • 如果檢測到URL模式,將調用一個視圖函數:views.index, 它是views.py文件中名為index() 的函數。
    • -
    - -

    path() 函數還指定一個name參數,它是此特定URL映射的唯一標識符。 您可以使用該名稱來“反向”映射器,即,動態創建指向映射器旨在處理的資源的URL。 例如,通過在模板中添加以下鏈接,我們可以使用name參數從任何其他頁面鏈接到我們的主頁:

    - -
    <a href="{% url 'index' %}">Home</a>.
    - -
    -

    注意: 我們可以對上面的鏈接進行硬編碼 (例如<a href="/catalog/">Home</a>), 但是如果我們更改主頁的模式 (例如更改為 /catalog/index) 則模板將不再 正確鏈接。 使用反向URL映射更加靈活和健壯!

    -
    - -

    View (function-based)

    - -

    View是一個用來處理 HTTP 請求的函式,根據需求從資料庫取得資料,通過使用 HTML 模板呈現此數據來生成 HTML , 並且在一個 HTTP 回應中返回 HTML 來呈現給用戶。Index view 遵循這個模型 — 獲取有關數據庫中有多少 Book, BookInstance, 可用的 BookInstance 還有 Author 的訊息, 然後把他們傳遞給模板進行顯示。

    - -

    打開catalog/views.py, 並且注意該文件已經導入 render() 快捷功能已使用模板和數據生成HTML文件。

    - -
    from django.shortcuts import render
    -
    -# Create your views here.
    -
    - -

    將以下代碼複製到文件底部。 第一行導入將用於訪問所有視圖中的數據的模型類。

    - -
    from .models import Book, Author, BookInstance, Genre
    -
    -def index(request):
    -    """View function for home page of site."""
    -
    -    # Generate counts of some of the main objects
    -    num_books = Book.objects.all().count()
    -    num_instances = BookInstance.objects.all().count()
    -
    -    # Available books (status = 'a')
    -    num_instances_available = BookInstance.objects.filter(status__exact='a').count()
    -
    -    # The 'all()' is implied by default.
    -    num_authors = Author.objects.count()
    -
    -    context = {
    -        'num_books': num_books,
    -        'num_instances': num_instances,
    -        'num_instances_available': num_instances_available,
    -        'num_authors': num_authors,
    -    }
    -
    -    # Render the HTML template index.html with the data in the context variable
    -    return render(request, 'index.html', context=context)
    - -

    視圖函數的第一部分使用模型類上的 objects.all() 屬性獲取記錄數。 它還獲取具有狀態字段值為“ a”(可用)的BookInstance 物件列表。 在上一教程(Django Tutorial Part 3: Using models > Searching for records)中,您可以找到更多有關如何從模型進行訪問的信息。.

    - -

    在函數的最後,我們調用 render() 函數來創建並返回HTML頁面作為響應(此快捷功能包裝了許多其他函數,從而簡化了這種非常常見的用例)。它以原始 request 物件 (一個 HttpRequest), 帶有數據佔位符的HTML模板以及上下文 context 變量包含將插入到這些佔位符中的數據的Python字典)為參數。

    - -

    在下一節中,我們將詳細討論模板和上下文變量。 讓我們開始創建模板,以便實際上可以向用戶顯示內容!

    - -

    Template

    - -

    模板是一個文本文件,用於定義文件(例如HTML頁面)的結構或佈局,並使用佔位符表示實際內容。 Django會在您的應用程序名為'templates'的目錄中自動查找模板。 因此,例如,在我們剛剛添加的索引視圖中, render() 函數將有望能夠找到文件 /locallibrary/catalog/templates/index.html,如果找不到該文件,則會引發錯誤。 如果您保存以前的更改並返回瀏覽器,則可以看到此信息-訪問127.0.0.1:8000現在將為您提供一個相當直觀的錯誤消息"TemplateDoesNotExist at /catalog/"以及其他詳細信息。

    - -
    -

    注意: Django將根據項目的設置文件在許多位置查找模板(搜索已安裝的應用程序是默認設置!)。 您可以在 Templates (Django docs)中找到有關Django如何查找模板及其支持的模板格式的更多信息。

    -
    - -

    Extending templates

    - -

    索引模板的頭部和身體將需要標準的HTML標記,以及用於導航的部分(到我們尚未創建的站點中的其他頁面)以及用於顯示一些介紹性文本和我們的書籍數據的部分。 對於我們網站上的每個頁面,大部分文本(HTML和導航結構)都是相同的。 Django模板語言允許您聲明一個基本模板,然後擴展它,而不是強迫開發人員在每個頁面中都複製此"樣板" ,只需替換每個特定頁面上不同的部分即可。

    - -

    例如,基本模板 base_generic.html 可能類似於以下文本。 如您所見,其中包含一些"通用" HTML以及標題,側邊欄和內容的部分,這些部分使用命名的blockendblock 模板標記進行了標記(以粗體顯示)。 區塊可以為空,或包含將在默認情況下用於派生頁面的內容。

    - -
    -

    注意:模板tags 類似於可以在模板中使用的功能,可以在模板中循環使用列表,基於變量的值執行條件操作等。除了模板標記之外,模板語法還允許您引用模板變量(傳遞給 模板),並使用template filters,該過濾器可重新格式化變量(例如,將字符串設置為小寫)。

    -
    - -
    <!DOCTYPE html>
    -<html lang="en">
    -<head>
    -  {% block title %}<title>Local Library</title>{% endblock %}
    -</head>
    -
    -<body>
    -  {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %}
    -  {% block content %}<!-- default content text (typically empty) -->{% endblock %}
    -</body>
    -</html>
    -
    - -

    當我們想為特定視圖定義模板時,我們首先指定基本模板(帶有extends 模板標籤-請參見下一個代碼清單)。 如果我們要在模板中替換任何節,則使用與基本模板中相同的block/endblock節來聲明這些節。

    - -

    例如,下面的代碼片段顯示了我們如何使用extends 模板標籤並覆蓋content 區塊。 生成的最終HTML將具有基本模板中定義的所有HTML和結構(包括您在title 區塊中定義的默認內容),但是將新的content 區塊插入到默認模板中。

    - -
    {% extends "base_generic.html" %}
    -
    -{% block content %}
    -  <h1>Local Library Home</h1>
    -  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
    -{% endblock %}
    - -

    The LocalLibrary base template

    - -

    下面列出了我們計劃用於LocalLibrary 網站的基本模板。 如您所見,其中包含一些HTML以及 title, sidebar, 和 content。 我們有一個默認標題(我們可能想要更改)和一個默認側邊欄,其中帶有指向所有書籍和作者列表的鏈接(我們可能不想更改,但是如果需要的話,我們允許範圍通過將其放在 在一個區塊中)。

    - -
    -

    注意: 我們還引入了兩個附加的模板標籤:urlload static。 這些將在以下各節中討論。

    -
    - -

    創建一個新文件/locallibrary/catalog/templates/base_generic.html ,並為其提供以下內容:

    - -
    <!DOCTYPE html>
    -<html lang="en">
    -<head>
    -  {% block title %}<title>Local Library</title>{% endblock %}
    -  <meta charset="utf-8">
    -  <meta name="viewport" content="width=device-width, initial-scale=1">
    -  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    -
    -  <!-- Add additional CSS in static file -->
    -  {% load static %}
    -  <link rel="stylesheet" href="{% static 'css/styles.css' %}">
    -</head>
    -<body>
    -  <div class="container-fluid">
    -    <div class="row">
    -      <div class="col-sm-2">
    -      {% block sidebar %}
    -      <ul class="sidebar-nav">
    -        <li><a href="{% url 'index' %}">Home</a></li>
    -        <li><a href="">All books</a></li>
    -        <li><a href="">All authors</a></li>
    -      </ul>
    -     {% endblock %}
    -      </div>
    -      <div class="col-sm-10 ">
    -      {% block content %}{% endblock %}
    -      </div>
    -    </div>
    -  </div>
    -</body>
    -</html>
    - -

    該模板包括來自Bootstrap的CSS,以改進HTML頁面的佈局和表示方式。 使用Bootstrap或其他客戶端Web框架是創建吸引人的頁面的快速方法,該頁面可以在不同的瀏覽器大小上很好地擴展。

    - -

    基本模板還引用了本地CSS文件 (styles.css) ,該文件提供了一些其他樣式。 創建 /locallibrary/catalog/static/css/styles.css並為其提供以下內容:

    - -
    .sidebar-nav {
    -    margin-top: 20px;
    -    padding: 0;
    -    list-style: none;
    -}
    - -

    The index template

    - -

    創建HTML文件 /locallibrary/catalog/templates/index.html 並為其提供以下內容。 如您所見,我們在第一行中擴展了基本模板,然後使用該模板的新內容塊替換默認content 區塊。

    - -
    {% extends "base_generic.html" %}
    -
    -{% block content %}
    -  <h1>Local Library Home</h1>
    -  <p>Welcome to LocalLibrary, a website developed by <em>Mozilla Developer Network</em>!</p>
    -
    -  <h2>Dynamic content</h2>
    -  <p>The library has the following record counts:</p>
    -  <ul>
    -    <li><strong>Books:</strong> \{{ num_books }}</li>
    -    <li><strong>Copies:</strong> \{{ num_instances }}</li>
    -    <li><strong>Copies available:</strong> \{{ num_instances_available }}</li>
    -    <li><strong>Authors:</strong> \{{ num_authors }}</li>
    -  </ul>
    -{% endblock %}
    - -

    Dynamic content 部分中,我們聲明了要從視圖中包含的信息的佔位符(template variables)。 變量使用“雙括號”或“把手”語法標記(請參見上面的粗體)。

    - -
    -

    注意:因為變量具有雙括號 (\{{ num_books }}),而標籤則用百分號括在單括號中擴展為 ({% extends "base_generic.html" %}),所以您可以輕鬆識別是要處理模板變量還是模板標籤(函數)。

    -
    - -

    這裡要注意的重要一點是,這些變量是使用我們在視圖的render() 函數中傳遞給context 字典的鍵命名的(請參見下文); 呈現模板時,這些將被其values 替換。

    - -
    context = {
    -    'num_books': num_books,
    -    'num_instances': num_instances,
    -    'num_instances_available': num_instances_available,
    -    'num_authors': num_authors,
    -}
    -
    -return render(request, 'index.html', context=context)
    - -

    Referencing static files in templates

    - -

    您的項目可能會使用靜態資源,包括JavaScript,CSS和圖像。 由於這些文件的位置可能未知(或可能會更改),因此Django允許您相對於STATIC_URL 全局設置在模板中指定這些文件的位置(默認框架網站將STATIC_URL 的值設置為'/static/',但您可以選擇將其託管在內容分發網絡或其他地方)。

    - -

    在模板中,您首先調用指定為“ static”的load 模板標籤以添加此模板庫(如下所示)。 加載靜態文件後,您可以使用static 模板標籤,指定感興趣文件的相對URL。

    - -
    <!-- Add additional CSS in static file -->
    -{% load static %}
    -<link rel="stylesheet" href="{% static 'css/styles.css' %}">
    - -

    如果需要,您可以以相同的方式將圖像添加到頁面中。 例如:

    - -
    {% load static %}
    -<img src="{% static 'catalog/images/local_library_model_uml.png' %}" alt="UML diagram" style="width:555px;height:540px;">
    -
    - -
    -

    注意:上面的更改指定了文件的位置,但是Django默認不提供文件。創建網站框架時 (created the website skeleton),雖然我們在全局URL映射器(/locallibrary/locallibrary/urls.py)中啟用了由開發Web服務器提供的服務,但您仍需要安排它們在生產中提供。 我們待會再看。

    -
    - -

    有關使用靜態文件的更多信息,請參閱管理靜態文件 Managing static files (Django docs)。

    - -

    Linking to URLs

    - -

    上面的基本模板引入了url 模板標籤。

    - -
    <li><a href="{% url 'index' %}">Home</a></li>
    -
    - -

    此標記採用在 urls.py中調用的 path()函數的名稱以及關聯視圖將從該函數接收的任何參數的值,並返回可用於鏈接到資源的URL。

    - -

    What does it look like?

    - -

    此時,我們應該已經創建了顯示索引頁面所需的所有內容。 運行服務器(python3 manage.py runserver),然後打開瀏覽器到http://127.0.0.1:8000/。 如果一切設置正確,則您的站點應類似於以下螢幕截圖。

    - -

    Index page for LocalLibrary website

    - -
    -

    注意:您將無法使用All booksAll authors鏈接,因為尚未定義這些頁面的路徑,視圖和模板(當前我們僅在base_generic.html html模板中插入了這些鏈接的佔位符)。

    -
    - -

    Challenge yourself

    - -

    這裡有兩個任務可以測試您對模型查詢,視圖和模板的熟悉程度。

    - -
      -
    1. LocalLibrary base template 已定義title 欄。 在 index template中覆蓋此塊並為頁面創建一些新標題。 - -
      -

      提示Extending templates 部分介紹瞭如何創建塊並將其擴展到另一個模板中。
      -

      -
      -
    2. -
    3. 修改 view以生成包含特定單詞(不區分大小寫)的流派計數和書籍計數,並將其傳遞給context (這與我們創建並使用num_booksnum_instances_available的方式大致相同)。 然後更新 index template 以使用這些變量。
    4. -
    - -
      -
    - -

    Summary

    - -

    現在,我們已經為網站創建了主頁-一個HTML頁面,該頁面顯示了數據庫中的一些記錄計數,並具有指向其他尚待創建頁面的鏈接。 在此過程中,我們學習了很多有關url映射器,視圖,使用我們的模型查詢數據庫,如何從視圖中將信息傳遞到模板以及如何創建和擴展模板的基本信息。

    - -

    在下一篇文章中,我們將基於我們的知識來創建其他四個頁面。

    - -

    See also

    - - - -

    {{PreviousMenuNext("Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django")}}

    - -

    In this module

    - - diff --git a/files/zh-tw/learn/server-side/django/home_page/index.md b/files/zh-tw/learn/server-side/django/home_page/index.md new file mode 100644 index 00000000000000..0d5c00ea22e458 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/home_page/index.md @@ -0,0 +1,373 @@ +--- +title: 'Django Tutorial Part 5: Creating our home page' +slug: Learn/Server-side/Django/Home_page +translation_of: Learn/Server-side/Django/Home_page +--- +{{LearnSidebar}}{{PreviousMenuNext("Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django")}} + +我們現在可以添加代碼,來顯示我們的第一個完整頁面 - [LocalLibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) 網站的主頁,顯示每個模型類型有多少條記錄,並提供我們其他頁面的側邊欄導航鏈接。一路上,我們將獲得編寫基本 URL 地圖和視圖、從數據庫獲取記錄、以及使用模板的實踐經驗。 + + + + + + + + + + + + +
    前提: + 讀 the + Django Introduction. 完成上章節 (including + Django Tutorial Part 4: Django admin site). +
    目的: + 了解如何創建簡單的URL映射和視圖(沒有數據編碼在URL中)以及如何從模型中獲取數據並創建模版。
    概要 +
    + +## 總覽 + +在定義了模型並創建了一些可以使用的初始庫記錄之後,是時候編寫將這些信息呈現給用戶的代碼了。 我們要做的第一件事是確定我們要在頁面中顯示的信息,並定義用於返回這些資源的 URL。 然後,我們將創建一個 URL 映射器,視圖和模板來顯示頁面。 + +下圖描述了主要數據流,以及處理 HTTP 請求和響應時所需的組件。 當我們已經實現了模型時,我們將創建的主要組件是: + +- URL 映射器將支持的 URL(以及 URL 中編碼的任何信息)轉發到適當的視圖功能。 +- 查看函數可從模型中獲取所需的數據,創建顯示數據的 HTML 頁面,並將頁面返回給用戶以在瀏覽器中查看。 +- 在視圖中呈現數據時要使用的模板。 + +![](basic-django.png) + +正如您將在下一節中看到的那樣,我們將顯示 5 頁,這是太多信息,無法在一篇文章中進行記錄。 因此,本文將重點介紹如何實現主頁,我們將在後續文章中介紹其他頁面。 這應該使您對 URL 映射器,視圖和模型在實踐中如何工作有很好的端到端理解。 + +## 定義資源 URL + +由於此版本的 LocalLibrary 對於最終用戶基本上是只讀的,因此我們只需要提供該網站的登錄頁面(主頁),以及顯示書籍和作者的列表和詳細視圖的頁面。 + +我們頁面所需的 URL 是: + +- `catalog/` — 主頁/索引頁面。 +- `catalog/books/` — 所有書籍的清單。 +- `catalog/authors/` — 所有作者列表。 +- `catalog/book/` — 特定書的詳細信息視圖,其主鍵為 `` (the default)。 因此,例如`/catalog/book/3`,作為添加的第三本書。 +- `catalog/author/` — 特定作者的詳細信息視圖,其主鍵字段名為 ``。 例如,為第 11 位作者添加了`/catalog/author/11`。 + +前三個 URL 用於列出索引,書籍和作者。 它們不對任何其他信息進行編碼,並且雖然返回的結果將取決於數據庫中的內容,但為獲取信息而運行的查詢將始終相同。 + +相比之下,最後兩個 URL 用於顯示有關特定書籍或作者的詳細信息-這些 URL 編碼要顯示在 URL 中的項目的標識(如上顯示為\)。 URL 映射器可以提取編碼信息並將其傳遞給視圖,然後將動態確定從數據庫中獲取哪些信息。 通過在我們的 URL 中編碼信息,我們只需要一個 URL 映射,視圖和模板即可處理每本書(或作者)。 + +> **備註:** Django 允許您以自己喜歡的任何方式來構造 URL-您可以如上所示在 URL 主體中編碼信息或使用 URL `GET` 參數(例如`/book/?id=6`)。 無論使用哪種方法,都應保持 URL 的整潔,邏輯和可讀性([在此處查看 W3C 建議](https://www.w3.org/Provider/Style/URI)). +> +> Django 文檔傾向於建議在 URL 正文中編碼信息,他們認為這種做法鼓勵更好的 URL 設計。 + +如概述中所述,本文的其餘部分描述瞭如何構造索引頁。 + +## 創建索引頁面 + +我們將創建的第一頁是索引頁 (`catalog/`)。 這將顯示一些靜態 HTML,以及數據庫中不同記錄的一些計算出的“計數”。 為了完成這項工作,我們必須創建一個 URL 映射,視圖和模板。 + +> **備註:** 值得在本節中多加註意。大多數材料是所有頁面共有的。 + +### URL mapping + +創建[skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) 時,我們更新了**locallibrary/urls.py**文件,以確保每當收到以 `catalog/` 開頭的 URL 時, _URLConf_ 模組 `catalog.urls` 都將處理其餘的子字符串。 + +來自 **locallibrary/urls.py**的以下代碼片段包括`catalog.urls` 模塊: + + urlpatterns += [ + path('catalog/', include('catalog.urls')), + ] + +> **備註:** 每當 Django 遇到導入函數 [`django.urls.include()`](https://docs.djangoproject.com/en/2.1/ref/urls/#django.urls.include)時,它都會在指定的結束字符處分割 URL 字符串,並將剩餘的子字符串發送到所包含的*URLconf* 模塊以進行進一步處理。 + +我們還為*URLConf* 模塊創建了一個佔位符文件,名為 **/catalog/urls.py**。 將以下行添加到該文件: + +```python +urlpatterns = [ + path('', views.index, name='index'), +] +``` + +`path()`函數定義以下內容: + +- URL 模式,它是一個空字符串:`''`。 處理其他視圖時,我們將詳細討論 URL 模式。 +- 如果檢測到 URL 模式,將調用一個視圖函數:`views.index`, 它是**views.py**文件中名為`index()` 的函數。 + +`path()` 函數還指定一個`name`參數,它是此特定 URL 映射的唯一標識符。 您可以使用該名稱來“反向”映射器,即,動態創建指向映射器旨在處理的資源的 URL。 例如,通過在模板中添加以下鏈接,我們可以使用 name 參數從任何其他頁面鏈接到我們的主頁: + +```html +Home. +``` + +> **備註:** 我們可以對上面的鏈接進行硬編碼 (例如`Home`), 但是如果我們更改主頁的模式 (例如更改為 `/catalog/index`) 則模板將不再 正確鏈接。 使用反向 URL 映射更加靈活和健壯! + +### View (function-based) + +View 是一個用來處理 HTTP 請求的函式,根據需求從資料庫取得資料,通過使用 HTML 模板呈現此數據來生成 HTML , 並且在一個 HTTP 回應中返回 HTML 來呈現給用戶。Index view 遵循這個模型 — 獲取有關數據庫中有多少 `Book`, `BookInstance`, 可用的 `BookInstance` 還有 `Author` 的訊息, 然後把他們傳遞給模板進行顯示。 + +打開**catalog/views.py**, 並且注意該文件已經導入 [render()](https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#django.shortcuts.render) 快捷功能已使用模板和數據生成 HTML 文件。 + +```python +from django.shortcuts import render + +# Create your views here. +``` + +將以下代碼複製到文件底部。 第一行導入將用於訪問所有視圖中的數據的模型類。 + +```python +from .models import Book, Author, BookInstance, Genre + +def index(request): + """View function for home page of site.""" + + # Generate counts of some of the main objects + num_books = Book.objects.all().count() + num_instances = BookInstance.objects.all().count() + + # Available books (status = 'a') + num_instances_available = BookInstance.objects.filter(status__exact='a').count() + + # The 'all()' is implied by default. + num_authors = Author.objects.count() + + context = { + 'num_books': num_books, + 'num_instances': num_instances, + 'num_instances_available': num_instances_available, + 'num_authors': num_authors, + } + + # Render the HTML template index.html with the data in the context variable + return render(request, 'index.html', context=context) +``` + +視圖函數的第一部分使用模型類上的 `objects.all()` 屬性獲取記錄數。 它還獲取具有狀態字段值為“ a”(可用)的`BookInstance` 物件列表。 在上一教程([Django Tutorial Part 3: Using models > Searching for records](/en-US/docs/Learn/Server-side/Django/Models#Searching_for_records))中,您可以找到更多有關如何從模型進行訪問的信息。. + +在函數的最後,我們調用 `render()` 函數來創建並返回 HTML 頁面作為響應(此快捷功能包裝了許多其他函數,從而簡化了這種非常常見的用例)。它以原始 `request` 物件 (一個 `HttpRequest`), 帶有數據佔位符的 HTML 模板以及上下文 `context` 變量包含將插入到這些佔位符中的數據的 Python 字典)為參數。 + +在下一節中,我們將詳細討論模板和上下文變量。 讓我們開始創建模板,以便實際上可以向用戶顯示內容! + +### Template + +模板是一個文本文件,用於定義文件(例如 HTML 頁面)的結構或佈局,並使用佔位符表示實際內容。 Django 會在您的應用程序名為'**templates**'的目錄中自動查找模板。 因此,例如,在我們剛剛添加的索引視圖中, `render()` 函數將有望能夠找到文件 **/locallibrary/catalog/templates/_index.html_**,如果找不到該文件,則會引發錯誤。 如果您保存以前的更改並返回瀏覽器,則可以看到此信息-訪問`127.0.0.1:8000`現在將為您提供一個相當直觀的錯誤消息"`TemplateDoesNotExist at /catalog/`"以及其他詳細信息。 + +> **備註:** Django 將根據項目的設置文件在許多位置查找模板(搜索已安裝的應用程序是默認設置!)。 您可以在 [Templates](https://docs.djangoproject.com/en/2.0/topics/templates/) (Django docs)中找到有關 Django 如何查找模板及其支持的模板格式的更多信息。 + +#### Extending templates + +索引模板的頭部和身體將需要標準的 HTML 標記,以及用於導航的部分(到我們尚未創建的站點中的其他頁面)以及用於顯示一些介紹性文本和我們的書籍數據的部分。 對於我們網站上的每個頁面,大部分文本(HTML 和導航結構)都是相同的。 Django 模板語言允許您聲明一個基本模板,然後擴展它,而不是強迫開發人員在每個頁面中都複製此"樣板" ,只需替換每個特定頁面上不同的部分即可。 + +例如,基本模板 **base_generic.html** 可能類似於以下文本。 如您所見,其中包含一些"通用" HTML 以及標題,側邊欄和內容的部分,這些部分使用命名的`block` 和`endblock` 模板標記進行了標記(以粗體顯示)。 區塊可以為空,或包含將在默認情況下用於派生頁面的內容。 + +> **備註:** 模板*tags* 類似於可以在模板中使用的功能,可以在模板中循環使用列表,基於變量的值執行條件操作等。除了模板標記之外,模板語法還允許您引用模板變量(傳遞給 模板),並使用*template filters*,該過濾器可重新格式化變量(例如,將字符串設置為小寫)。 + +```html + + + + {% block title %}Local Library{% endblock %} + + + + {% block sidebar %}{% endblock %} + {% block content %}{% endblock %} + + +``` + +當我們想為特定視圖定義模板時,我們首先指定基本模板(帶有`extends` 模板標籤-請參見下一個代碼清單)。 如果我們要在模板中替換任何節,則使用與基本模板中相同的`block`/`endblock`節來聲明這些節。 + +例如,下面的代碼片段顯示了我們如何使用`extends` 模板標籤並覆蓋`content` 區塊。 生成的最終 HTML 將具有基本模板中定義的所有 HTML 和結構(包括您在`title` 區塊中定義的默認內容),但是將新的`content` 區塊插入到默認模板中。 + +```html +{% extends "base_generic.html" %} + +{% block content %} +

    Local Library Home

    +

    Welcome to LocalLibrary, a website developed by Mozilla Developer Network!

    +{% endblock %} +``` + +#### The LocalLibrary base template + +下面列出了我們計劃用於*LocalLibrary* 網站的基本模板。 如您所見,其中包含一些 HTML 以及 `title`, `sidebar`, 和 `content`。 我們有一個默認標題(我們可能想要更改)和一個默認側邊欄,其中帶有指向所有書籍和作者列表的鏈接(我們可能不想更改,但是如果需要的話,我們允許範圍通過將其放在 在一個區塊中)。 + +> **備註:** 我們還引入了兩個附加的模板標籤:`url` 和`load static`。 這些將在以下各節中討論。 + +創建一個新文件**/locallibrary/catalog/templates/_base_generic.html_** ,並為其提供以下內容: + +```html + + + + {% block title %}Local Library{% endblock %} + + + + + + {% load static %} + + + +
    +
    +
    + {% block sidebar %} + + {% endblock %} +
    +
    + {% block content %}{% endblock %} +
    +
    +
    + + +``` + +該模板包括來自[Bootstrap](http://getbootstrap.com/)的 CSS,以改進 HTML 頁面的佈局和表示方式。 使用 Bootstrap 或其他客戶端 Web 框架是創建吸引人的頁面的快速方法,該頁面可以在不同的瀏覽器大小上很好地擴展。 + +基本模板還引用了本地 CSS 文件 (**styles.css**) ,該文件提供了一些其他樣式。 創建 **/locallibrary/catalog/static/css/styles.css**並為其提供以下內容: + +```css +.sidebar-nav { + margin-top: 20px; + padding: 0; + list-style: none; +} +``` + +#### The index template + +創建 HTML 文件 **/locallibrary/catalog/templates/_index.html_** 並為其提供以下內容。 如您所見,我們在第一行中擴展了基本模板,然後使用該模板的新內容塊替換默認`content` 區塊。 + +```html +{% extends "base_generic.html" %} + +{% block content %} +

    Local Library Home

    +

    Welcome to LocalLibrary, a website developed by Mozilla Developer Network!

    + +

    Dynamic content

    +

    The library has the following record counts:

    +
      +
    • Books: \{{ num_books }}
    • +
    • Copies: \{{ num_instances }}
    • +
    • Copies available: \{{ num_instances_available }}
    • +
    • Authors: \{{ num_authors }}
    • +
    +{% endblock %} +``` + +在 _Dynamic content_ 部分中,我們聲明了要從視圖中包含的信息的佔位符(_template variables_)。 變量使用“雙括號”或“把手”語法標記(請參見上面的粗體)。 + +> **備註:** 因為變量具有雙括號 (`\{{ num_books }}`),而標籤則用百分號括在單括號中擴展為 (`{% extends "base_generic.html" %}`),所以您可以輕鬆識別是要處理模板變量還是模板標籤(函數)。 + +這裡要注意的重要一點是,這些變量是使用我們在視圖的`render()` 函數中傳遞給`context` 字典的鍵命名的(請參見下文); 呈現模板時,這些將被其*values* 替換。 + +```python +context = { + 'num_books': num_books, + 'num_instances': num_instances, + 'num_instances_available': num_instances_available, + 'num_authors': num_authors, +} + +return render(request, 'index.html', context=context) +``` + +#### Referencing static files in templates + +您的項目可能會使用靜態資源,包括 JavaScript,CSS 和圖像。 由於這些文件的位置可能未知(或可能會更改),因此 Django 允許您相對於`STATIC_URL` 全局設置在模板中指定這些文件的位置(默認框架網站將`STATIC_URL` 的值設置為'`/static/`',但您可以選擇將其託管在內容分發網絡或其他地方)。 + +在模板中,您首先調用指定為“ static”的`load` 模板標籤以添加此模板庫(如下所示)。 加載靜態文件後,您可以使用`static` 模板標籤,指定感興趣文件的相對 URL。 + +```html + +{% load static %} + +``` + +如果需要,您可以以相同的方式將圖像添加到頁面中。 例如: + +```html +{% load static %} +UML diagram +``` + +> **備註:** 上面的更改指定了文件的位置,但是 Django 默認不提供文件。創建網站框架時 ([created the website skeleton](/en-US/docs/Learn/Server-side/Django/skeleton_website)),雖然我們在全局 URL 映射器(**/locallibrary/locallibrary/urls.py**)中啟用了由開發 Web 服務器提供的服務,但您仍需要安排它們在生產中提供。 我們待會再看。 + +有關使用靜態文件的更多信息,請參閱管理靜態文件 [Managing static files](https://docs.djangoproject.com/en/2.0/howto/static-files/) (Django docs)。 + +#### Linking to URLs + +上面的基本模板引入了`url` 模板標籤。 + +```python +
  • Home
  • +``` + +此標記採用在 **urls.py**中調用的 `path()`函數的名稱以及關聯視圖將從該函數接收的任何參數的值,並返回可用於鏈接到資源的 URL。 + +## What does it look like? + +此時,我們應該已經創建了顯示索引頁面所需的所有內容。 運行服務器(`python3 manage.py runserver`),然後打開瀏覽器到。 如果一切設置正確,則您的站點應類似於以下螢幕截圖。 + +![Index page for LocalLibrary website](index_page_ok.png) + +> **備註:** 您將無法使用**All books**和**All authors**鏈接,因為尚未定義這些頁面的路徑,視圖和模板(當前我們僅在`base_generic.html` html 模板中插入了這些鏈接的佔位符)。 + +## Challenge yourself + +這裡有兩個任務可以測試您對模型查詢,視圖和模板的熟悉程度。 + +1. LocalLibrary [base template](#The_LocalLibrary_base_template) 已定義`title` 欄。 在 [index template](#The_index_template)中覆蓋此塊並為頁面創建一些新標題。 + + > **備註:** [Extending templates](#Extending_templates) 部分介紹瞭如何創建塊並將其擴展到另一個模板中。 + +2. 修改 [view](<#View_(function-based)>)以生成包含特定單詞(不區分大小寫)的流派計數和書籍計數,並將其傳遞給`context` (這與我們創建並使用`num_books` 和`num_instances_available`的方式大致相同)。 然後更新 [index template](#The_index_template) 以使用這些變量。 + +## Summary + +現在,我們已經為網站創建了主頁-一個 HTML 頁面,該頁面顯示了數據庫中的一些記錄計數,並具有指向其他尚待創建頁面的鏈接。 在此過程中,我們學習了很多有關 url 映射器,視圖,使用我們的模型查詢數據庫,如何從視圖中將信息傳遞到模板以及如何創建和擴展模板的基本信息。 + +在下一篇文章中,我們將基於我們的知識來創建其他四個頁面。 + +## See also + +- [Writing your first Django app, part 3: Views and Templates](https://docs.djangoproject.com/en/2.0/intro/tutorial03/) (Django docs) +- [URL dispatcher](https://docs.djangoproject.com/en/2.0/topics/http/urls/) (Django docs) +- [View functions](https://docs.djangoproject.com/en/2.0/topics/http/views/) (DJango docs) +- [Templates](https://docs.djangoproject.com/en/2.0/topics/templates/) (Django docs) +- [Managing static files](https://docs.djangoproject.com/en/2.0/howto/static-files/) (Django docs) +- [Django shortcut functions](https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#django.shortcuts.render) (Django docs) + +{{PreviousMenuNext("Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django")}} + +## In this module + +- [Django introduction](/en-US/docs/Learn/Server-side/Django/Introduction) +- [Setting up a Django development environment](/en-US/docs/Learn/Server-side/Django/development_environment) +- [Django Tutorial: The Local Library website](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django Tutorial Part 2: Creating a skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) +- [Django Tutorial Part 3: Using models](/en-US/docs/Learn/Server-side/Django/Models) +- [Django Tutorial Part 4: Django admin site](/en-US/docs/Learn/Server-side/Django/Admin_site) +- [Django Tutorial Part 5: Creating our home page](/en-US/docs/Learn/Server-side/Django/Home_page) +- [Django Tutorial Part 6: Generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views) +- [Django Tutorial Part 7: Sessions framework](/en-US/docs/Learn/Server-side/Django/Sessions) +- [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/Authentication) +- [Django Tutorial Part 9: Working with forms](/en-US/docs/Learn/Server-side/Django/Forms) +- [Django Tutorial Part 10: Testing a Django web application](/en-US/docs/Learn/Server-side/Django/Testing) +- [Django Tutorial Part 11: Deploying Django to production](/en-US/docs/Learn/Server-side/Django/Deployment) +- [Django web application security](/en-US/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django mini blog](/en-US/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/index.html b/files/zh-tw/learn/server-side/django/index.html deleted file mode 100644 index 9e2aa434dad6ba..00000000000000 --- a/files/zh-tw/learn/server-side/django/index.html +++ /dev/null @@ -1,115 +0,0 @@ ---- -title: Django 網站框架 (Python) -slug: Learn/Server-side/Django -translation_of: Learn/Server-side/Django ---- -
    {{LearnSidebar}}
    - -

    Django 使用 Python 語言編寫,是一個廣受歡迎、且功能完整的服務器端網站框架。本模塊將為您展示,為什麼 Django 能夠成為一個廣受歡迎的服務器端框架,如何設置開發環境,以及如何開始創建你自己的網絡應用。

    - -

    先決條件

    - -

    開始學習本模塊,並不需要任何 Django 知識. 但您要理解什麼是服務器端網絡編程、什麼是網絡框架,最好能夠閱讀我們的服務端網站編程的第一步模塊

    - -

    最好能有基本的編程概念、並了解 Python 語言,但並不是理解本教程的核心概念的必然條件。

    - -
    -

    Note: 對於初學者來說,Python 是最容易閱讀和理解的編程語言之一。也就是說,如果您想更好的理解本教程,網上有很多免費書籍及免費教程可供參考學習(建議初學者查看 Python 官網的 Python for Non Programmers )。

    -
    - -

    指引

    - -
    -
    Django 簡介
    -
    在第一篇關於 Django 的文章裡,我們會回答"什麼是Django?",並概述這個網絡框架的特殊之處。我們會列出主要的功能,包括一些高級的功能特性,這些高級特性我們在這部分教程裡沒有時間詳細說明。在你設置好 Django 應用、並開始把玩它之前,我們會展示 Django 應用的一些主要模塊,讓你明白 Django 應用能做什麼。
    -
    架設 Django 開發環境
    -
    現在你知道 Django 是做什麼的,我們會展示怎樣在 Windows、Linux(Ubuntu)、和 Mac OS X上,創建和測試 Django 的開發環境—不管你是用什麼操作系統,這篇文章會教給你能夠開發 Django 應用所需要的開發環境。
    -
    Django 教學 1: 本地圖書館網站
    -
    我們實用教程系列的第一篇文章,會解釋你將學習到什麼,並提供 "本地圖書館" 網站這個例子的概述。我們會在接下來的文章裡,完成並不斷的改進這個網站。
    -
    Django 教學 2: 創建骨架網站
    -
    這篇文章會教你,怎樣創建一個網站的 "框架" 。以這個網站為基礎,你可以填充網站特定的 settings、urls、models、views 和 templates。
    -
    Django 教學 3: 使用模型
    -
    這篇文章會為 “本地圖書館網站” 定義數據模板—數據模板是我們為應用存儲的數據結構。並且允許 Django 在資料庫中存儲數據(以後可以修改)。此文章解釋了什麼是數據模板、怎樣聲明它、和一些主要的數據種類。文章還簡要的介紹了一些,你可以獲得數據模板的方法。
    -
    Django 教學 4: Django 管理員頁面
    -
    現在我們已經為本地圖書館網站,創建了模型,我們將使用 Django 管理員頁面添加一些 ‘真實的’ 的圖書數據。首先,我們將向你介紹,如何使用管理員頁面註冊模型,然後我們介紹如何登錄和創建一些數據。最後我們展示一些,進一步改進管理員頁面呈現的方法。
    -
    Django 教學 5: 創建我們的首頁
    -
    我們現在可以添加代碼,來展示我們的第一個完整頁面—本地圖書館主頁,來顯示我們對每個模型類型有多少條記錄,並提供我們其他頁面的側邊欄導航鏈接。一路上,我們將獲得編寫基本 URL 地圖和視圖、從數據庫獲取記錄、以及使用模版的實踐經驗。.
    -
    Django 教學 6: 通用列表與詳細視圖
    -
    本教學課程擴展了我們的本地圖書館網站,添加書籍和作者和詳細頁面。在這裡,我們將了解基於類別的通用視圖,並展示如何減少常用代碼用例的代碼量。我們還將更詳細地深入理解 URL 處理,展示如何執行基本模式匹配。
    -
    Django 教學 7: 會話框架
    -
    本教學擴展本地圖書館網站,向首頁添加了一個基於會話的訪問計數器。這是個比較簡單的例子,但它顯示如何使用會話框架,為你自己的網站中的匿名用戶,提供一致的行為。
    -
    Django 教學 8: 使用者身份驗証和權限
    -
    本教程,我們將向你展示,如何允許使用者用自己的賬戶,登錄到你的網站,以及如何根據他們是否登錄、及其權限,來控制他們可以做什麼、和看到什麼。作為此次演示的一部分,我們將擴展本地圖書館網站,添加登錄和登出頁面,以及使用者和工作人員特定頁面,以查看已借用的書籍。
    -
    Django 教學 9: 使用表單
    -
    本教程,我們將向你展示如何使用 Django 中的 HTML Forms 表單,特別是編寫表單以創建、更新、和刪除模型實例的最簡單方法。作為此次演示的一部分,我們將擴展本地圖書館網站,以便圖書館員,可以使用我們自己的表單 (而不是使用管理應用程序) 來更新書籍,創建、更新、刪除作者。
    -
    Django 教學 10: 測試 Django 網頁應用
    -
    隨著網站的的發展,手工測試越來越難測試—不僅要測試更多,而且隨著組件之間的相互作用變得越來越複雜,一個領域的一個小的變化,可能需要許多額外的測試,來驗證其對其他領域的影響。減輕這些問題的一種方法,是編寫自動化測試,每次更改時,都可以輕鬆可靠地運行。本教程將介紹如何使用 Django 的測試框架,對你的網站進行單元測試自動化。
    -
    Django 教學 11: 部署 Django 到生產環境
    -
    現在,你已創建(並測試)一個很酷的 “本地圖書館網站”,你將要把它安裝在公共 Web 服務器上,以便圖書館員工和成員,可以通過 Internet 訪問。本文概述如何找到主機,來部署你的網站,以及你需要做什麼,才能使你的網站準備好投入生產環境。
    -
    Django 網頁應用安全
    -
    保護用戶數據,是任何網站設計的重要組成部分,我們以前解釋了Web 安全文章中,一些更常見的安全威脅—本文提供了 Django 內置、如何保護處理這種危險的實際演示。
    -
    - -

    評估

    - -

    以下評估,將測試你對如何使用 Django 創建網站的理解,如上述指南中所列出的項目。

    - -
    -
    DIY Django 微博客
    -
    在這個評估中,你將使用你從本單元中學到的一些知識,來創建自己的博客。
    -
    -
    {{LearnSidebar}}
    - -

    Django 使用 Python 語言編寫,是一個廣受歡迎、且功能完整的服務器端網站框架。本模塊將為您展示,為什麼 Django 能夠成為一個廣受歡迎的服務器端框架,如何設置開發環境,以及如何開始創建你自己的網絡應用。

    - -

    先決條件

    - -

    開始學習本模塊,並不需要任何 Django 知識. 但您要理解什麼是服務器端網絡編程、什麼是網絡框架,最好能夠閱讀我們的服務端網站編程的第一步模塊

    - -

    最好能有基本的編程概念、並了解 Python 語言,但並不是理解本教程的核心概念的必然條件。

    - -
    -

    Note: 對於初學者來說,Python 是最容易閱讀和理解的編程語言之一。也就是說,如果您想更好的理解本教程,網上有很多免費書籍及免費教程可供參考學習(建議初學者查看 Python 官網的 Python for Non Programmers )。

    -
    - -

    指引

    - -
    -
    Django 簡介
    -
    在第一篇關於 Django 的文章裡,我們會回答"什麼是Django?",並概述這個網絡框架的特殊之處。我們會列出主要的功能,包括一些高級的功能特性,這些高級特性我們在這部分教程裡沒有時間詳細說明。在你設置好 Django 應用、並開始把玩它之前,我們會展示 Django 應用的一些主要模塊,讓你明白 Django 應用能做什麼。
    -
    架設 Django 開發環境
    -
    現在你知道 Django 是做什麼的,我們會展示怎樣在 Windows、Linux(Ubuntu)、和 Mac OS X上,創建和測試 Django 的開發環境—不管你是用什麼操作系統,這篇文章會教給你能夠開發 Django 應用所需要的開發環境。
    -
    Django 教學 1: 本地圖書館網站
    -
    我們實用教程系列的第一篇文章,會解釋你將學習到什麼,並提供 "本地圖書館" 網站這個例子的概述。我們會在接下來的文章裡,完成並不斷的改進這個網站。
    -
    Django 教學 2: 創建骨架網站
    -
    這篇文章會教你,怎樣創建一個網站的 "框架" 。以這個網站為基礎,你可以填充網站特定的 settings、urls、models、views 和 templates。
    -
    Django 教學 3: 使用模型
    -
    這篇文章會為 “本地圖書館網站” 定義數據模板—數據模板是我們為應用存儲的數據結構。並且允許 Django 在資料庫中存儲數據(以後可以修改)。此文章解釋了什麼是數據模板、怎樣聲明它、和一些主要的數據種類。文章還簡要的介紹了一些,你可以獲得數據模板的方法。
    -
    Django 教學 4: Django 管理員頁面
    -
    現在我們已經為本地圖書館網站,創建了模型,我們將使用 Django 管理員頁面添加一些 ‘真實的’ 的圖書數據。首先,我們將向你介紹,如何使用管理員頁面註冊模型,然後我們介紹如何登錄和創建一些數據。最後我們展示一些,進一步改進管理員頁面呈現的方法。
    -
    Django 教學 5: 創建我們的首頁
    -
    我們現在可以添加代碼,來展示我們的第一個完整頁面—本地圖書館主頁,來顯示我們對每個模型類型有多少條記錄,並提供我們其他頁面的側邊欄導航鏈接。一路上,我們將獲得編寫基本 URL 地圖和視圖、從數據庫獲取記錄、以及使用模版的實踐經驗。.
    -
    Django 教學 6: 通用列表與詳細視圖
    -
    本教學課程擴展了我們的本地圖書館網站,添加書籍和作者和詳細頁面。在這裡,我們將了解基於類別的通用視圖,並展示如何減少常用代碼用例的代碼量。我們還將更詳細地深入理解 URL 處理,展示如何執行基本模式匹配。
    -
    Django 教學 7: 會話框架
    -
    本教學擴展本地圖書館網站,向首頁添加了一個基於會話的訪問計數器。這是個比較簡單的例子,但它顯示如何使用會話框架,為你自己的網站中的匿名用戶,提供一致的行為。
    -
    Django 教學 8: 使用者身份驗証和權限
    -
    本教程,我們將向你展示,如何允許使用者用自己的賬戶,登錄到你的網站,以及如何根據他們是否登錄、及其權限,來控制他們可以做什麼、和看到什麼。作為此次演示的一部分,我們將擴展本地圖書館網站,添加登錄和登出頁面,以及使用者和工作人員特定頁面,以查看已借用的書籍。
    -
    Django 教學 9: 使用表單
    -
    本教程,我們將向你展示如何使用 Django 中的 HTML Forms 表單,特別是編寫表單以創建、更新、和刪除模型實例的最簡單方法。作為此次演示的一部分,我們將擴展本地圖書館網站,以便圖書館員,可以使用我們自己的表單 (而不是使用管理應用程序) 來更新書籍,創建、更新、刪除作者。
    -
    Django 教學 10: 測試 Django 網頁應用
    -
    隨著網站的的發展,手工測試越來越難測試—不僅要測試更多,而且隨著組件之間的相互作用變得越來越複雜,一個領域的一個小的變化,可能需要許多額外的測試,來驗證其對其他領域的影響。減輕這些問題的一種方法,是編寫自動化測試,每次更改時,都可以輕鬆可靠地運行。本教程將介紹如何使用 Django 的測試框架,對你的網站進行單元測試自動化。
    -
    Django 教學 11: 部署 Django 到生產環境
    -
    現在,你已創建(並測試)一個很酷的 “本地圖書館網站”,你將要把它安裝在公共 Web 服務器上,以便圖書館員工和成員,可以通過 Internet 訪問。本文概述如何找到主機,來部署你的網站,以及你需要做什麼,才能使你的網站準備好投入生產環境。
    -
    Django 網頁應用安全
    -
    保護用戶數據,是任何網站設計的重要組成部分,我們以前解釋了 Web 安全文章中,一些更常見的安全威脅—本文提供了 Django 內置、如何保護處理這種危險的實際演示。
    -
    - -

    評估

    - -

    以下評估,將測試你對如何使用 Django 創建網站的理解,如上述指南中所列出的項目。

    - -
    -
    Django 小部落格 DIY
    -
    在這個評估中,你將使用你從本單元中學到的一些知識,來創建自己的部落格。
    -
    diff --git a/files/zh-tw/learn/server-side/django/index.md b/files/zh-tw/learn/server-side/django/index.md new file mode 100644 index 00000000000000..83fb19235af004 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/index.md @@ -0,0 +1,104 @@ +--- +title: Django 網站框架 (Python) +slug: Learn/Server-side/Django +translation_of: Learn/Server-side/Django +--- +{{LearnSidebar}} + +Django 使用 Python 語言編寫,是一個廣受歡迎、且功能完整的服務器端網站框架。本模塊將為您展示,為什麼 Django 能夠成為一個廣受歡迎的服務器端框架,如何設置開發環境,以及如何開始創建你自己的網絡應用。 + +## 先決條件 + +開始學習本模塊,並不需要任何 Django 知識. 但您要理解什麼是服務器端網絡編程、什麼是網絡框架,最好能夠閱讀我們的[服務端網站編程的第一步模塊](/zh-TW/docs/Learn/Server-side/First_steps)。 + +最好能有基本的編程概念、並了解 [Python](/zh-TW/docs/Glossary/Python) 語言,但並不是理解本教程的核心概念的必然條件。 + +> **備註:** 對於初學者來說,Python 是最容易閱讀和理解的編程語言之一。也就是說,如果您想更好的理解本教程,網上有很多免費書籍及免費教程可供參考學習(建議初學者查看 Python 官網的 [Python for Non Programmers](https://wiki.python.org/moin/BeginnersGuide/NonProgrammers) )。 + +## 指引 + +- [Django 簡介](/zh-TW/docs/Learn/Server-side/Django/Introduction) + - : 在第一篇關於 Django 的文章裡,我們會回答"什麼是 Django?",並概述這個網絡框架的特殊之處。我們會列出主要的功能,包括一些高級的功能特性,這些高級特性我們在這部分教程裡沒有時間詳細說明。在你設置好 Django 應用、並開始把玩它之前,我們會展示 Django 應用的一些主要模塊,讓你明白 Django 應用能做什麼。 +- [架設 Django 開發環境](/zh-TW/docs/Learn/Server-side/Django/development_environment) + - : 現在你知道 Django 是做什麼的,我們會展示怎樣在 Windows、Linux(Ubuntu)、和 Mac OS X 上,創建和測試 Django 的開發環境—不管你是用什麼操作系統,這篇文章會教給你能夠開發 Django 應用所需要的開發環境。 +- [Django 教學 1: 本地圖書館網站](/zh-TW/docs/Learn/Server-side/Django/Tutorial_local_library_website) + - : 我們實用教程系列的第一篇文章,會解釋你將學習到什麼,並提供 "本地圖書館" 網站這個例子的概述。我們會在接下來的文章裡,完成並不斷的改進這個網站。 +- [Django 教學 2: 創建骨架網站](/zh-TW/docs/Learn/Server-side/Django/skeleton_website) + - : 這篇文章會教你,怎樣創建一個網站的 "框架" 。以這個網站為基礎,你可以填充網站特定的 settings、urls、models、views 和 templates。 +- [Django 教學 3: 使用模型](/zh-TW/docs/Learn/Server-side/Django/Models) + - : 這篇文章會為 “本地圖書館網站” 定義數據模板—數據模板是我們為應用存儲的數據結構。並且允許 Django 在資料庫中存儲數據(以後可以修改)。此文章解釋了什麼是數據模板、怎樣聲明它、和一些主要的數據種類。文章還簡要的介紹了一些,你可以獲得數據模板的方法。 +- [Django 教學 4: Django 管理員頁面](/zh-TW/docs/Learn/Server-side/Django/Admin_site) + - : 現在我們已經為本地圖書館網站,創建了模型,我們將使用 Django 管理員頁面添加一些 ‘真實的’ 的圖書數據。首先,我們將向你介紹,如何使用管理員頁面註冊模型,然後我們介紹如何登錄和創建一些數據。最後我們展示一些,進一步改進管理員頁面呈現的方法。 +- [Django 教學 5: 創建我們的首頁](/zh-TW/docs/Learn/Server-side/Django/Home_page) + - : 我們現在可以添加代碼,來展示我們的第一個完整頁面—本地圖書館主頁,來顯示我們對每個模型類型有多少條記錄,並提供我們其他頁面的側邊欄導航鏈接。一路上,我們將獲得編寫基本 URL 地圖和視圖、從數據庫獲取記錄、以及使用模版的實踐經驗。. +- [Django 教學 6: 通用列表與詳細視圖](/zh-TW/docs/Learn/Server-side/Django/Generic_views) + - : 本教學課程擴展了我們的本地圖書館網站,添加書籍和作者和詳細頁面。在這裡,我們將了解基於類別的通用視圖,並展示如何減少常用代碼用例的代碼量。我們還將更詳細地深入理解 URL 處理,展示如何執行基本模式匹配。 +- [Django 教學 7: 會話框架](/zh-TW/docs/Learn/Server-side/Django/Sessions) + - : 本教學擴展本地圖書館網站,向首頁添加了一個基於會話的訪問計數器。這是個比較簡單的例子,但它顯示如何使用會話框架,為你自己的網站中的匿名用戶,提供一致的行為。 +- [Django 教學 8: 使用者身份驗証和權限](/zh-TW/docs/Learn/Server-side/Django/Authentication) + - : 本教程,我們將向你展示,如何允許使用者用自己的賬戶,登錄到你的網站,以及如何根據他們是否登錄、及其權限,來控制他們可以做什麼、和看到什麼。作為此次演示的一部分,我們將擴展本地圖書館網站,添加登錄和登出頁面,以及使用者和工作人員特定頁面,以查看已借用的書籍。 +- [Django 教學 9: 使用表單](/zh-TW/docs/Learn/Server-side/Django/Forms) + - : 本教程,我們將向你展示如何使用 Django 中的 [HTML Forms](/zh-TW/docs/Web/Guide/HTML/Forms) 表單,特別是編寫表單以創建、更新、和刪除模型實例的最簡單方法。作為此次演示的一部分,我們將擴展本地圖書館網站,以便圖書館員,可以使用我們自己的表單 (而不是使用管理應用程序) 來更新書籍,創建、更新、刪除作者。 +- [Django 教學 10: 測試 Django 網頁應用](/zh-TW/docs/Learn/Server-side/Django/Testing) + - : 隨著網站的的發展,手工測試越來越難測試—不僅要測試更多,而且隨著組件之間的相互作用變得越來越複雜,一個領域的一個小的變化,可能需要許多額外的測試,來驗證其對其他領域的影響。減輕這些問題的一種方法,是編寫自動化測試,每次更改時,都可以輕鬆可靠地運行。本教程將介紹如何使用 Django 的測試框架,對你的網站進行單元測試自動化。 +- [Django 教學 11: 部署 Django 到生產環境](/zh-TW/docs/Learn/Server-side/Django/Deployment) + - : 現在,你已創建(並測試)一個很酷的 “本地圖書館網站”,你將要把它安裝在公共 Web 服務器上,以便圖書館員工和成員,可以通過 Internet 訪問。本文概述如何找到主機,來部署你的網站,以及你需要做什麼,才能使你的網站準備好投入生產環境。 +- [Django 網頁應用安全](/zh-TW/docs/Learn/Server-side/Django/web_application_security) + - : 保護用戶數據,是任何網站設計的重要組成部分,我們以前解釋了 Web 安全文章中,一些更常見的安全威脅—本文提供了 Django 內置、如何保護處理這種危險的實際演示。 + +## 評估 + +以下評估,將測試你對如何使用 Django 創建網站的理解,如上述指南中所列出的項目。 + +- [DIY Django 微博客](/zh-TW/docs/Learn/Server-side/Django/django_assessment_blog) + - : 在這個評估中,你將使用你從本單元中學到的一些知識,來創建自己的博客。 + +{{LearnSidebar}} + +Django 使用 Python 語言編寫,是一個廣受歡迎、且功能完整的服務器端網站框架。本模塊將為您展示,為什麼 Django 能夠成為一個廣受歡迎的服務器端框架,如何設置開發環境,以及如何開始創建你自己的網絡應用。 + +## 先決條件 + +開始學習本模塊,並不需要任何 Django 知識. 但您要理解什麼是服務器端網絡編程、什麼是網絡框架,最好能夠閱讀我們的[服務端網站編程的第一步模塊](/zh-TW/docs/Learn/Server-side/First_steps)。 + +最好能有基本的編程概念、並了解 [Python](/zh-TW/docs/Glossary/Python) 語言,但並不是理解本教程的核心概念的必然條件。 + +> **備註:** 對於初學者來說,Python 是最容易閱讀和理解的編程語言之一。也就是說,如果您想更好的理解本教程,網上有很多免費書籍及免費教程可供參考學習(建議初學者查看 Python 官網的 [Python for Non Programmers](https://wiki.python.org/moin/BeginnersGuide/NonProgrammers) )。 + +## 指引 + +- [Django 簡介](/zh-TW/docs/Learn/Server-side/Django/Introduction) + - : 在第一篇關於 Django 的文章裡,我們會回答"什麼是 Django?",並概述這個網絡框架的特殊之處。我們會列出主要的功能,包括一些高級的功能特性,這些高級特性我們在這部分教程裡沒有時間詳細說明。在你設置好 Django 應用、並開始把玩它之前,我們會展示 Django 應用的一些主要模塊,讓你明白 Django 應用能做什麼。 +- [架設 Django 開發環境](/zh-TW/docs/Learn/Server-side/Django/development_environment) + - : 現在你知道 Django 是做什麼的,我們會展示怎樣在 Windows、Linux(Ubuntu)、和 Mac OS X 上,創建和測試 Django 的開發環境—不管你是用什麼操作系統,這篇文章會教給你能夠開發 Django 應用所需要的開發環境。 +- [Django 教學 1: 本地圖書館網站](/zh-TW/docs/Learn/Server-side/Django/Tutorial_local_library_website) + - : 我們實用教程系列的第一篇文章,會解釋你將學習到什麼,並提供 "本地圖書館" 網站這個例子的概述。我們會在接下來的文章裡,完成並不斷的改進這個網站。 +- [Django 教學 2: 創建骨架網站](/zh-TW/docs/Learn/Server-side/Django/skeleton_website) + - : 這篇文章會教你,怎樣創建一個網站的 "框架" 。以這個網站為基礎,你可以填充網站特定的 settings、urls、models、views 和 templates。 +- [Django 教學 3: 使用模型](/zh-TW/docs/Learn/Server-side/Django/Models) + - : 這篇文章會為 “本地圖書館網站” 定義數據模板—數據模板是我們為應用存儲的數據結構。並且允許 Django 在資料庫中存儲數據(以後可以修改)。此文章解釋了什麼是數據模板、怎樣聲明它、和一些主要的數據種類。文章還簡要的介紹了一些,你可以獲得數據模板的方法。 +- [Django 教學 4: Django 管理員頁面](/zh-TW/docs/Learn/Server-side/Django/Admin_site) + - : 現在我們已經為本地圖書館網站,創建了模型,我們將使用 Django 管理員頁面添加一些 ‘真實的’ 的圖書數據。首先,我們將向你介紹,如何使用管理員頁面註冊模型,然後我們介紹如何登錄和創建一些數據。最後我們展示一些,進一步改進管理員頁面呈現的方法。 +- [Django 教學 5: 創建我們的首頁](/zh-TW/docs/Learn/Server-side/Django/Home_page) + - : 我們現在可以添加代碼,來展示我們的第一個完整頁面—本地圖書館主頁,來顯示我們對每個模型類型有多少條記錄,並提供我們其他頁面的側邊欄導航鏈接。一路上,我們將獲得編寫基本 URL 地圖和視圖、從數據庫獲取記錄、以及使用模版的實踐經驗。. +- [Django 教學 6: 通用列表與詳細視圖](/zh-TW/docs/Learn/Server-side/Django/Generic_views) + - : 本教學課程擴展了我們的本地圖書館網站,添加書籍和作者和詳細頁面。在這裡,我們將了解基於類別的通用視圖,並展示如何減少常用代碼用例的代碼量。我們還將更詳細地深入理解 URL 處理,展示如何執行基本模式匹配。 +- [Django 教學 7: 會話框架](/zh-TW/docs/Learn/Server-side/Django/Sessions) + - : 本教學擴展本地圖書館網站,向首頁添加了一個基於會話的訪問計數器。這是個比較簡單的例子,但它顯示如何使用會話框架,為你自己的網站中的匿名用戶,提供一致的行為。 +- [Django 教學 8: 使用者身份驗証和權限](/zh-TW/docs/Learn/Server-side/Django/Authentication) + - : 本教程,我們將向你展示,如何允許使用者用自己的賬戶,登錄到你的網站,以及如何根據他們是否登錄、及其權限,來控制他們可以做什麼、和看到什麼。作為此次演示的一部分,我們將擴展本地圖書館網站,添加登錄和登出頁面,以及使用者和工作人員特定頁面,以查看已借用的書籍。 +- [Django 教學 9: 使用表單](/zh-TW/docs/Learn/Server-side/Django/Forms) + - : 本教程,我們將向你展示如何使用 Django 中的 [HTML Forms](/zh-TW/docs/Web/Guide/HTML/Forms) 表單,特別是編寫表單以創建、更新、和刪除模型實例的最簡單方法。作為此次演示的一部分,我們將擴展本地圖書館網站,以便圖書館員,可以使用我們自己的表單 (而不是使用管理應用程序) 來更新書籍,創建、更新、刪除作者。 +- [Django 教學 10: 測試 Django 網頁應用](/zh-TW/docs/Learn/Server-side/Django/Testing) + - : 隨著網站的的發展,手工測試越來越難測試—不僅要測試更多,而且隨著組件之間的相互作用變得越來越複雜,一個領域的一個小的變化,可能需要許多額外的測試,來驗證其對其他領域的影響。減輕這些問題的一種方法,是編寫自動化測試,每次更改時,都可以輕鬆可靠地運行。本教程將介紹如何使用 Django 的測試框架,對你的網站進行單元測試自動化。 +- [Django 教學 11: 部署 Django 到生產環境](/zh-TW/docs/Learn/Server-side/Django/Deployment) + - : 現在,你已創建(並測試)一個很酷的 “本地圖書館網站”,你將要把它安裝在公共 Web 服務器上,以便圖書館員工和成員,可以通過 Internet 訪問。本文概述如何找到主機,來部署你的網站,以及你需要做什麼,才能使你的網站準備好投入生產環境。 +- [Django 網頁應用安全](/zh-TW/docs/Learn/Server-side/Django/web_application_security) + - : 保護用戶數據,是任何網站設計的重要組成部分,我們以前解釋了 Web 安全文章中,一些更常見的安全威脅—本文提供了 Django 內置、如何保護處理這種危險的實際演示。 + +## 評估 + +以下評估,將測試你對如何使用 Django 創建網站的理解,如上述指南中所列出的項目。 + +- [Django 小部落格 DIY](/zh-TW/docs/Learn/Server-side/Django/django_assessment_blog) + - : 在這個評估中,你將使用你從本單元中學到的一些知識,來創建自己的部落格。 diff --git a/files/zh-tw/learn/server-side/django/introduction/index.html b/files/zh-tw/learn/server-side/django/introduction/index.html deleted file mode 100644 index f23fd45163f0a2..00000000000000 --- a/files/zh-tw/learn/server-side/django/introduction/index.html +++ /dev/null @@ -1,306 +0,0 @@ ---- -title: Django 介紹 -slug: Learn/Server-side/Django/Introduction -translation_of: Learn/Server-side/Django/Introduction ---- -
    {{LearnSidebar}}
    - -
    {{NextMenu("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django")}}
    - -

    在這第一篇Django文章中,我們將回答“什麼是Django”這個問題,並概述這個網絡框架有什麼特性。我們將描述主要功能,包括一些高級功能,但我們並不會在本單元中詳細介紹。我們還會展示一些Django應用程序的主要構建模塊(儘管此時你還沒有要測試的開發環境)。

    - - - - - - - - - - - - -
    先備知識:基本的電腦知識.對服務器端網站編程的一般了解 ,特別是網站中客戶端-服務器交互的機制 .
    目標:了解Django是什麼,它提供了哪些功能,以及Django應用程序的主要構建塊。
    - -

    什麼是 Django?

    - -

    Django 是一個高級的 Python 網路框架,可以快速開發安全和可維護的網站。由經驗豐富的開發者構建,Django 負責處理網站開發中麻煩的部分,因此你可以專注於編寫應用程序,而無需重新開發。

    - -

    它是免費和開源的,有活躍繁榮的社區、豐富的文檔、以及很多免費和付費的解決方案。

    - -

    Django 可以使你的應用具有以下優點:

    - -
    -
    完備
    -
    Django 遵循 “功能完備” 的理念,提供開發人員可能想要 “開箱即用” 的幾乎所有功能。因為你需要的一切,都是一個 ”產品“ 的一部分,它們都可以無縫結合在一起,遵循一致性設計原則,並且具有廣泛、和最新的文檔
    -
    通用
    -
    -

    Django 可以(並已經)用於構建幾乎任何類型的網站—從內容管理系統和維基,到社交網絡和新聞網站。它可以與任何客戶端框架一起工作,並且可以提供幾乎任何格式(包括 HTML、RSS、JSON、XML等)的內容。你正在閱讀的網站就是基於 Django。

    - -

    在內部,儘管它為幾乎所有可能需要的功能(例如幾個流行的資料庫,模版引擎等)提供了選擇,但是如果需要,它也可以擴展到使用其他組件。

    -
    -
    安全
    -
    -

    Django 幫助開發人員,通過提供一個被設計為 “做正確的事情” 來自動保護網站的框架,來避免許多常見的安全錯誤。例如,Django 提供了一種安全的方式,來管理用戶帳號和密碼,避免了常見的錯誤,比如將 session 放在 cookie 中這種易受攻擊的做法(取而代之的是,cookies 只包含一個密鑰,實際數據存儲在數據庫中),或直接存儲密碼,而不是密碼的 hash 值。

    - -

    密碼 hash ,是讓密碼通過加密 hash 函數,而創建的固定長度值。 Django 能通過運行 hash 函數,來檢查輸入的密碼 - 就是將輸出的 hash 值,與存儲的 hash 值進行比較是否正確。然而由於功能的 “單向” 性質,假使存儲的 hash 值受到威脅,攻擊者也難以解出原始密碼。 (但其實有彩虹表-譯者觀點)

    - -

    默認情況下,Django 可以防範許多漏洞,包括 SQL 注入,跨站點腳本,跨站點請求偽造,和點擊劫持 (請參閱 網站安全 相關信息,如有興趣)。

    -
    -
    可擴展
    -
    Django 使用基於組件的 “無共享” 架構 (架構的每一部分獨立於其他架構,因此可以根據需要進行替換或更改)。在不同部分之間,有明確的分隔,意味著它可以通過在任何級別添加硬件,來擴展服務:緩存服務器,數據庫服務器,或應用程序服務器。一些最繁忙的網站,已經在 Django 架構下成功地縮放了網站的規模大小,以滿足他們的需求(例如 Instagram 和 Disqus,僅舉兩個例子,可自行添加)。
    -
    可維護
    -
    Django 代碼編寫,是遵照設計原則和模式,鼓勵創建可維護和可重複使用的代碼。特別是,它使用了不要重複自己(DRY)原則,所以沒有不必要的重複,減少了代碼的數量。 Django 還將相關功能,分組到可重用的 “應用程序” 中,並且在較低級別,將相關代碼分組或模塊( 模型視圖控制器 Model View Controller (MVC) 模式)。
    -
    可移植
    -
    Django 是用 Python 編寫的,它在許多平台上運行。這意味著,你不受任務特定的服務器平台的限制,並且可以在許多種類的 Linux,Windows 和 Mac OS X 上運行應用程序。此外,Django 得到許多網路託管提供商的好評,他們經常提供特定的基礎設施,和託管 Django 網站的文檔。
    -
    - -

    Django的起源?

    - -

    Django 最初在 2003 年到 2005 年間,由負責創建和維護報紙網站的網絡團隊開發。在創建了許多網站後,團隊開始考慮、並重用許多常見的代碼和設計模式。這個共同的代碼,演變一個通用的網絡開發框架,2005 年 7 月,被開源為 “Django” 項目。

    - -

    Django 不斷發展壯大 — 從 2008 年 9 月的第一個里程碑版本(1.0),到最近發布的(2.0)-(2018)版本。每個版本都添加了新功能,和錯誤修復,從支持新類型的數據庫,模版引擎和緩存,到添加 “通用” 視圖函數和類別(這減少了開發人員在一些編程任務必須編寫的代碼量)。

    - -
    -

    注意: 查看 Django 網站上的發行說明 release notes,看看最近版本發生了什麼變化,以及 Django 能做多少工作

    -
    - -

    Django 現在是一個蓬勃發展的合作開源項目,擁有數千個用戶和貢獻者。雖然它仍然具有反映其起源的一些功能,但 Django 已經發展成為,能夠開發任何類型的網站的多功能框架。

    - -

    Django有多受歡迎?

    - -

    服務器端框架的受歡迎程度沒有任何可靠和明確的測量(儘管Hot Frameworks網站嘗試使用諸如計算每個平台的GitHub項目數量和StackOverflow問題的機制來評估流行度)。一個更好的問題是Django是否“足夠流行”,以避免不受歡迎的平台的問題。它是否繼續發展?如果您需要幫助,可以幫您嗎?如果您學習Django,有機會獲得付費工作嗎?

    - -

    基於使用Django的流行網站數量,為代碼庫貢獻的人數以及提供免費和付費支持的人數,那麼是的,Django是一個流行的框架!

    - -

    使用Django的流行網站包括:Disqus,Instagram,騎士基金會,麥克阿瑟基金會,Mozilla,國家地理,開放知識基金會,Pinterest和開放棧(來源:Django home page ).

    - -

    Django 是特定用途的?

    - -

    Web框架通常將自己稱為“特定”或“無限制”。

    - -

    特定框架是對處理任何特定任務的“正確方法”有意見的框架。他們經常支持特定領域的快速發展(解決特定類型的問題),因為正確的做法是通常被很好地理解和記錄在案。然而,他們在解決其主要領域之外的問題時可能不那麼靈活,並且傾向於為可以使用哪些組件和方法提供較少的選擇。

    - -

    相比之下,无限制的框架对于将组件粘合在一起以实现目标或甚至应使用哪些组件的最佳方式的限制较少。它们使开发人员更容易使用最合适的工具来完成特定任务,尽管您需要自己查找这些组件。

    - -

    Django“有點有意義”,因此提供了“兩個世界的最佳”。它提供了一組組件來處理大多數Web開發任務和一個(或兩個)首選的使用方法。然而,Django的解耦架構意味著您通常可以從多個不同的選項中進行選擇,也可以根據需要添加對全新的支持。

    - -

    Django 代碼是什麼樣子?

    - -

    在傳統的數據驅動網站中,Web應用程序會等待來自Web瀏覽器(或其他客戶端)的HTTP 請求。當接收到請求時,應用程序根據URL 和可能的POST 數據或GET 數據中的信息確定需要的內容。根據需要,可以從數據庫讀取或寫入信息,或執行滿足請求所需的其他任務。然後,該應用程序將返回對Web瀏覽器的響應,通常通過將檢索到的數據插入HTML模板中的佔位符來動態創建用於瀏覽器顯示的HTML 頁面。

    - -

    Django 網絡應用程序通常將處理每個步驟的代碼分組到單獨的文件中:

    - -

    - -
      -
    • URLs: 雖然可以通過單個功能來處理來自每個URL的請求,但是編寫單獨的視圖函數來處理每個資源是更加可維護的。URL映射器用於根據請求URL將HTTP請求重定向到相應的視圖。URL映射器還可以匹配出現在URL中的字符串或數字的特定模式,並將其作為數據傳遞給視圖功能。
      -
    • -
    • View: 視圖是一個請求處理函數,它接收HTTP請求並返回HTTP響應。視圖通過模型訪問滿足請求所需的數據,並將響應的格式委託給模板。
      -
    • -
    • Models: 模型是定義應用程序數據結構的Python對象,並提供在數據庫中管理(添加,修改,刪除)和查詢記錄的機制。
      -
    • -
    • Templates: 模板是定義文件(例如HTML頁面)的結構或佈局的文本文件,用於表示實際內容的佔位符。一個視圖可以使用HTML模板,從數據填充它動態地創建一個HTML頁面模型。可以使用模板來定義任何類型的文件的結構;它不一定是HTML!
    • -
    - -
    -

    注意 : Django將此組織稱為“模型視圖模板(MVT)”架構。它與更加熟悉的Model View Controller架構有許多相似之處.

    -
    - -
      -
    - -

    以下部分將為您提供Django應用程序的這些主要部分的想法(稍後我們將在進一步詳細介紹後,我們將在開發環境中進行更詳細的介紹)。

    - -

    將請求發送到正確的視圖(urls.py)

    - -

    URL映射器通常存儲在名為urls.py的文件中。在下面的示例中,mapper(urlpatterns)定義了特定URL 模式和相應視圖函數之間的映射列表。如果接收到具有與指定模式匹配的URL(例如r'^$',下面)的HTTP請求,則將調用相關聯的視圖功能(例如 views.index)並傳遞請求。

    - -
    urlpatterns = [
    -    path('admin/', admin.site.urls),
    -    path('book/<int:id>/', views.book_detail, name='book_detail'),
    -    path('catalog/', include('catalog.urls')),
    -    re_path(r'^([0-9]+)/$', views.best),
    -]
    -
    - -

    urlpatterns對像是path()和/或re_path()函數的列表(Python列表使用方括號定義,其中項目用逗號分隔,可以有一個可選的尾隨逗號。例如:[item1, item2, item3, ])。

    - -

    兩種方法的第一個參數,是將要匹配的路由(模式)。 path()方法使用尖括號,來定義將被捕獲、並作為命名參數傳遞給視圖函數的 URL 的部分。 re_path()函數使用靈活的模式匹配方法,稱為正則表達式。我們將在後面的文章中討論這些內容!

    - -

    第二個參數,是在匹配模式時將調用的另一個函數。註釋 views.book_detail表示該函數名為book_detail(),可以在名為views的模塊中找到(即在名為views.py的文件中)

    - -

    處理請求(views.py)

    - - - -

    視圖是Web應用程序的核心,從Web客戶端接收HTTP請求並返回HTTP響應。在兩者之間,他們編制框架的其他資源來訪問數據庫,渲染模板等。

    - -

    下面的例子顯示了一個最小的視圖功能index(),這可以通過我們的URL映射器在上一節中調用。像所有視圖函數一樣,它接收一個HttpRequest對像作為參數(request)並返回一個HttpResponse對象。在這種情況下,我們對請求不做任何事情,我們的響應只是返回一個硬編碼的字符串。我們會向您顯示一個請求,在稍後的部分中會提供更有趣的內容。

    - - - -
    ## filename: views.py (Django view functions)
    -
    -from django.http import HttpResponse
    -
    -def index(request):
    -    # Get an HttpRequest - the request parameter
    -    # perform operations using information from the request.
    -    # Return HttpResponse
    -    return HttpResponse('Hello from Django!')
    -
    - -
    -

    注意 :一點點Python:

    - -
      -
    • Python模塊是函數的“庫”,存放在單獨的文件中,我們可能希望在代碼中使用。在這裡,我們只導入了HttpResponse從對象django.http模塊,使我們可以在視圖中使用
      - from django.http import HttpResponse
      - 還有其他方法可以從模塊導入一些或所有對象
    • -
    • 使用def,如上所示的關鍵字聲明函數,命參數在函數名稱後面的括號中列出:整行以冒號結尾。注意下一行是否都縮進。縮進很重要,因為它指定代碼行在該特定塊內(強制縮進是Python的一個關鍵特徵,而且是Python代碼很容易閱讀的一個原因)。
    • -
    - - -
    - -
      -
    - -

    視圖通常存放在一個名為views.py的文件中。

    - -

    定義數據模型(models.py)

    - - - -

    Django Web應用程序,通過被稱為模型的Python對象,來管理和查詢數據。模型定義存儲數據的結構,包括字段類型 以及字段可能的最大值,默認值,選擇列表選項,文檔幫助文本,表單的標籤文本等。模型的定義與底層數據庫無關-您可以選擇其中一個,作為項目設置的一部分。一旦您選擇了要使用的數據庫,您就不需要直接與之交談- 只需編寫模型結構和其他代碼,Django可以處理與數據庫通信的所有辛苦的工作。

    - -

    下面的代碼片段為Team對象,展示了一個非常簡單的Django模型。本Team類別是從Django的類別派生models.Model。它將團隊名稱和團隊級別,定義為字符字段,並為每個記錄指定了要存放的最大字符數。team_level可以是幾個值中的一個,因此,我們將其定義為一個選擇字段,並在被展示的數據、和被儲存的數據之間,建立映射,並設置一個默認值。

    - - - -
    # filename: models.py
    -
    -from django.db import models
    -
    -class Team(models.Model):
    -    team_name = models.CharField(max_length=40)
    -
    -    TEAM_LEVELS = (
    -        ('U09', 'Under 09s'),
    -        ('U10', 'Under 10s'),
    -        ('U11', 'Under 11s'),
    -        ...  #list other team levels
    -    )
    -    team_level = models.CharField(max_length=3,choices=TEAM_LEVELS,default='U11')
    -
    - -
    -

    注意 : Python小知識:

    - -
      -
    • Python支持“面向對象編程”,這是一種編程風格,我們將代碼組織到對像中,其中包括用於對該對象進行操作的相關數據和功能。對像也可以從其他對象繼承/擴展/派生,允許相關對象之間的共同行為被共享。在Python中,我們使用關鍵字Class定義對象的“藍圖”。我們可以根據類中的模型創建類型的多個特定實例。
    • -
    • 例如,我們有個Team類,它來自於Model類。這意味著它是一個模型,並且將包含模型的所有方法,但是我們也可以給它自己的專門功能。在我們的模型中,我們定義了我們的數據庫需要存儲我們的數據字段,給出它們的具體名稱。Django使用這些定義(包括字段名稱)來創建底層數據庫。
    • -
    - - -
    - -

    查詢數據(views.py)

    - - - -

    Django模型提供了一個,用於搜索數據庫的簡單查詢API。這可以使用不同的標準(例如,精確,不區分大小寫,大於等等)來匹配多個字段,並且可以支持複雜語句(例如,您可以在擁有一個團隊的U11團隊上指定搜索名稱以“Fr ”開頭或以“al”結尾)。

    - -

    代碼片段顯示了一個視圖函數(資源處理程序),用於顯示我們所有的U09團隊。粗體顯示如何使用模型查詢API,過濾所有記錄,其中該 team_level字段,具有正確的文本“ U09 ”(請注意,該條件如何filter()作為參數傳遞給該函數,該字段名稱和匹配類型由雙下劃線: team_level__exact

    - - - -
    ## filename: views.py
    -
    -from django.shortcuts import render
    -from .models import Team
    -
    -def index(request):
    -    list_teams = Team.objects.filter(team_level__exact="U09")
    -    context = {'youngest_teams': list_teams}
    -    return render(request, '/best/index.html', context)
    -
    - -
    -
    - -

    此功能使用render ()功能創建HttpResponse發送回瀏覽器的功能。這個函數是一個快捷方式;它通過組合指定的HTML模版和一些數據來插入模版(在名為“ content ”的變量中提供)來創建一個HTML文件。在下一節中,我們將介紹如何在其中插入數據以創建HTML

    - -

    呈現數據(HTML模版)

    - -

    模板系統允許您使用佔位符指定輸出文檔的結構,以便在生成頁面時填充數據。模板通常用於創建HTML,但也可以創建其他類型的文檔。 Django支持其本機模板系統,和另一個流行的Python庫,名為 Jinja2(如果需要,它也可以支持其他系統)。

    - -

    代碼片段,顯示了上一節中render()函數調用的HTML模板的外觀。這個模板的編寫假設它在渲染時可以訪問名為youngest_teams的列表變量(包含在上面render()函數中的上下文變量context中)。在HTML框架內部,我們有一個表達式,首先檢查youngest_teams變量是否存在,然後在for循環中迭代它。在每次迭代中,模板在{{htmlelement("li")}}元素中顯示每個團隊的team_name值。

    - -
    ## filename: best/templates/best/index.html
    -
    -<!DOCTYPE html>
    -<html lang="en">
    -<body>
    -
    - {% if youngest_teams %}
    -    <ul>
    -    {% for team in youngest_teams %}
    -        <li>\{\{ team.team_name \}\}</li>
    -    {% endfor %}
    -    </ul>
    -{% else %}
    -    <p>No teams are available.</p>
    -{% endif %}
    -
    -</body>
    -</html>
    - -

    你還能做什麼?

    - - - -

    前面的部分,展示了幾乎每個Web應用程序將使用的主要功能:URL映射,視圖,模型和模版。Django提供的其他內容包括:

    - -
      -
    • 表單 : HTML表單用於收集用戶數據,以便在服務器上進行處理。Django簡化了表單創建,驗證和處理。
    • -
    • 用戶身份驗證和權限 : Django包含了一個強大的用戶身份驗證和權限系統,該系統已經構建了安全性。
    • -
    • 緩存 :與提供靜態內容相比,動態創建內容需要更大的計算強度(也更緩慢)。Django提供靈活的緩存,以便你可以存儲所有或部分的頁面。如無必要,不會重新呈現網頁。
    • -
    • 管理網站 :當你使用基本骨架創建應用時,就已經默認包含了一個Django管理站點。它十分輕鬆地創建了一個管理頁面,使網站管理員能夠創建、編輯和查看站點中的任何數據模型。
    • -
    • 序列化數據 : Django可以輕鬆地將數據序列化,並支持XML或JSON格式。這會有助於創建一個Web服務(Web服務指數據純粹為其他應用程序或站點所用,並不會在自己的站點中顯示),或是有助於創建一個由客戶端代碼處理、和呈現所有數據的網站。
    • -
    - - - -

    總結

    - - - -

    恭喜,您已經完成了Django之旅的第一步!您現在應該了解Django的主要優點,一些關於它的歷史,以及Django應用程序的每個主要部分可能是什麼樣子。您還應該了解Python編程語言的一些內容,包括列表,函數和類別的語法。

    - -

    您已經看到上面的一些真正的Django代碼,但與客戶端代碼不同,您需要設置一個開發環境來運行它。這是我們的下一步。

    - - - -
    {{NextMenu("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django")}}
    - -

    本教學連結

    - - diff --git a/files/zh-tw/learn/server-side/django/introduction/index.md b/files/zh-tw/learn/server-side/django/introduction/index.md new file mode 100644 index 00000000000000..51c5e653596c8a --- /dev/null +++ b/files/zh-tw/learn/server-side/django/introduction/index.md @@ -0,0 +1,266 @@ +--- +title: Django 介紹 +slug: Learn/Server-side/Django/Introduction +translation_of: Learn/Server-side/Django/Introduction +--- +{{LearnSidebar}}{{NextMenu("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django")}} + +在這第一篇 Django 文章中,我們將回答“什麼是 Django”這個問題,並概述這個網絡框架有什麼特性。我們將描述主要功能,包括一些高級功能,但我們並不會在本單元中詳細介紹。我們還會展示一些 Django 應用程序的主要構建模塊(儘管此時你還沒有要測試的開發環境)。 + + + + + + + + + + + + +
    先備知識: + 基本的電腦知識.對服務器端網站編程的一般了解 + ,特別是網站中客戶端-服務器交互的機制 + . +
    目標: + 了解Django是什麼,它提供了哪些功能,以及Django應用程序的主要構建塊。 +
    + +## 什麼是 Django? + +Django 是一個高級的 Python 網路框架,可以快速開發安全和可維護的網站。由經驗豐富的開發者構建,Django 負責處理網站開發中麻煩的部分,因此你可以專注於編寫應用程序,而無需重新開發。 + +它是免費和開源的,有活躍繁榮的社區、豐富的文檔、以及很多免費和付費的解決方案。 + +Django 可以使你的應用具有以下優點: + +- 完備 + - : Django 遵循 “功能完備” 的理念,提供開發人員可能想要 “開箱即用” 的幾乎所有功能。因為你需要的一切,都是一個 ”產品“ 的一部分,它們都可以無縫結合在一起,遵循一致性設計原則,並且具有廣泛、和[最新的文檔](https://docs.djangoproject.com/en/2.0/)。 +- 通用 + + - : Django 可以(並已經)用於構建幾乎任何類型的網站—從內容管理系統和維基,到社交網絡和新聞網站。它可以與任何客戶端框架一起工作,並且可以提供幾乎任何格式(包括 HTML、RSS、JSON、XML 等)的內容。你正在閱讀的網站就是基於 Django。 + + 在內部,儘管它為幾乎所有可能需要的功能(例如幾個流行的資料庫,模版引擎等)提供了選擇,但是如果需要,它也可以擴展到使用其他組件。 + +- 安全 + + - : Django 幫助開發人員,通過提供一個被設計為 “做正確的事情” 來自動保護網站的框架,來避免許多常見的安全錯誤。例如,Django 提供了一種安全的方式,來管理用戶帳號和密碼,避免了常見的錯誤,比如將 session 放在 cookie 中這種易受攻擊的做法(取而代之的是,cookies 只包含一個密鑰,實際數據存儲在數據庫中),或直接存儲密碼,而不是密碼的 hash 值。 + + 密碼 hash ,是讓密碼通過加密 hash 函數,而創建的固定長度值。 Django 能通過運行 hash 函數,來檢查輸入的密碼 - 就是將輸出的 hash 值,與存儲的 hash 值進行比較是否正確。然而由於功能的 “單向” 性質,假使存儲的 hash 值受到威脅,攻擊者也難以解出原始密碼。 (但其實有彩虹表-譯者觀點) + + 默認情況下,Django 可以防範許多漏洞,包括 SQL 注入,跨站點腳本,跨站點請求偽造,和點擊劫持 (請參閱 網站安全 相關信息,如有興趣)。 + +- 可擴展 + - : Django 使用基於組件的 “無共享” 架構 (架構的每一部分獨立於其他架構,因此可以根據需要進行替換或更改)。在不同部分之間,有明確的分隔,意味著它可以通過在任何級別添加硬件,來擴展服務:緩存服務器,數據庫服務器,或應用程序服務器。一些最繁忙的網站,已經在 Django 架構下成功地縮放了網站的規模大小,以滿足他們的需求(例如 Instagram 和 Disqus,僅舉兩個例子,可自行添加)。 +- 可維護 + - : Django 代碼編寫,是遵照設計原則和模式,鼓勵創建可維護和可重複使用的代碼。特別是,它使用了不要重複自己(DRY)原則,所以沒有不必要的重複,減少了代碼的數量。 Django 還將相關功能,分組到可重用的 “應用程序” 中,並且在較低級別,將相關代碼分組或模塊( 模型視圖控制器 [Model View Controller (MVC)](/en-US/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture) 模式)。 +- 可移植 + - : Django 是用 Python 編寫的,它在許多平台上運行。這意味著,你不受任務特定的服務器平台的限制,並且可以在許多種類的 Linux,Windows 和 Mac OS X 上運行應用程序。此外,Django 得到許多網路託管提供商的好評,他們經常提供特定的基礎設施,和託管 Django 網站的文檔。 + +## Django 的起源? + +Django 最初在 2003 年到 2005 年間,由負責創建和維護報紙網站的網絡團隊開發。在創建了許多網站後,團隊開始考慮、並重用許多常見的代碼和設計模式。這個共同的代碼,演變一個通用的網絡開發框架,2005 年 7 月,被開源為 “Django” 項目。 + +Django 不斷發展壯大 — 從 2008 年 9 月的第一個里程碑版本(1.0),到最近發布的(2.0)-(2018)版本。每個版本都添加了新功能,和錯誤修復,從支持新類型的數據庫,模版引擎和緩存,到添加 “通用” 視圖函數和類別(這減少了開發人員在一些編程任務必須編寫的代碼量)。 + +> **備註:** 查看 Django 網站上的發行說明 [release notes](https://docs.djangoproject.com/en/2.0/releases/),看看最近版本發生了什麼變化,以及 Django 能做多少工作 + +Django 現在是一個蓬勃發展的合作開源項目,擁有數千個用戶和貢獻者。雖然它仍然具有反映其起源的一些功能,但 Django 已經發展成為,能夠開發任何類型的網站的多功能框架。 + +## Django 有多受歡迎? + +服務器端框架的受歡迎程度沒有任何可靠和明確的測量(儘管[Hot Frameworks](http://hotframeworks.com/)網站嘗試使用諸如計算每個平台的 GitHub 項目數量和 StackOverflow 問題的機制來評估流行度)。一個更好的問題是 Django 是否“足夠流行”,以避免不受歡迎的平台的問題。它是否繼續發展?如果您需要幫助,可以幫您嗎?如果您學習 Django,有機會獲得付費工作嗎? + +基於使用 Django 的流行網站數量,為代碼庫貢獻的人數以及提供免費和付費支持的人數,那麼是的,Django 是一個流行的框架! + +使用 Django 的流行網站包括:Disqus,Instagram,騎士基金會,麥克阿瑟基金會,Mozilla,國家地理,開放知識基金會,Pinterest 和開放棧(來源:[Django home page](https://www.djangoproject.com/) ). + +## Django 是特定用途的? + +Web 框架通常將自己稱為“特定”或“無限制”。 + +特定框架是對處理任何特定任務的“正確方法”有意見的框架。他們經常支持特定領域的快速發展(解決特定類型的問題),因為正確的做法是通常被很好地理解和記錄在案。然而,他們在解決其主要領域之外的問題時可能不那麼靈活,並且傾向於為可以使用哪些組件和方法提供較少的選擇。 + +相比之下,无限制的框架对于将组件粘合在一起以实现目标或甚至应使用哪些组件的最佳方式的限制较少。它们使开发人员更容易使用最合适的工具来完成特定任务,尽管您需要自己查找这些组件。 + +Django“有點有意義”,因此提供了“兩個世界的最佳”。它提供了一組組件來處理大多數 Web 開發任務和一個(或兩個)首選的使用方法。然而,Django 的解耦架構意味著您通常可以從多個不同的選項中進行選擇,也可以根據需要添加對全新的支持。 + +## Django 代碼是什麼樣子? + +在傳統的數據驅動網站中,Web 應用程序會等待來自 Web 瀏覽器(或其他客戶端)的 HTTP 請求。當接收到請求時,應用程序根據 URL 和可能的`POST` 數據或`GET` 數據中的信息確定需要的內容。根據需要,可以從數據庫讀取或寫入信息,或執行滿足請求所需的其他任務。然後,該應用程序將返回對 Web 瀏覽器的響應,通常通過將檢索到的數據插入 HTML 模板中的佔位符來動態創建用於瀏覽器顯示的 HTML 頁面。 + +Django 網絡應用程序通常將處理每個步驟的代碼分組到單獨的文件中: + +![](basic-django.png) + +- **URLs:** 雖然可以通過單個功能來處理來自每個 URL 的請求,但是編寫單獨的視圖函數來處理每個資源是更加可維護的。URL 映射器用於根據請求 URL 將 HTTP 請求重定向到相應的視圖。URL 映射器還可以匹配出現在 URL 中的字符串或數字的特定模式,並將其作為數據傳遞給視圖功能。 + +- **View:** 視圖是一個請求處理函數,它接收 HTTP 請求並返回 HTTP 響應。視圖通過模型訪問滿足請求所需的數據,並將響應的格式委託給模板。 + +- **Models:** 模型是定義應用程序數據結構的 Python 對象,並提供在數據庫中管理(添加,修改,刪除)和查詢記錄的機制。 + +- **Templates:** 模板是定義文件(例如 HTML 頁面)的結構或佈局的文本文件,用於表示實際內容的佔位符。一個視圖可以使用 HTML 模板,從數據填充它動態地創建一個 HTML 頁面模型。可以使用模板來定義任何類型的文件的結構;它不一定是 HTML! + +> **備註:** Django 將此組織稱為“模型視圖模板(MVT)”架構。它與更加熟悉的[Model View Controller](/en-US/docs/Web/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture)架構有許多相似之處. + +以下部分將為您提供 Django 應用程序的這些主要部分的想法(稍後我們將在進一步詳細介紹後,我們將在開發環境中進行更詳細的介紹)。 + +### 將請求發送到正確的視圖(urls.py) + +URL 映射器通常存儲在名為 urls.py 的文件中。在下面的示例中,mapper(`urlpatterns`)定義了特定 URL 模式和相應視圖函數之間的映射列表。如果接收到具有與指定模式匹配的 URL(例如 r'^$',下面)的 HTTP 請求,則將調用相關聯的視圖功能(例如 views.index)並傳遞請求。 + + urlpatterns = [ + path('admin/', admin.site.urls), + path('book//', views.book_detail, name='book_detail'), + path('catalog/', include('catalog.urls')), + re_path(r'^([0-9]+)/$', views.best), + ] + +`urlpatterns`對像是`path()`和/或`re_path()`函數的列表(Python 列表使用方括號定義,其中項目用逗號分隔,可以有一個[可選的尾隨逗號](https://docs.python.org/2/faq/design.html#why-does-python-allow-commas-at-the-end-of-lists-and-tuples)。例如:\[`item1, item2, item3,` ])。 + +兩種方法的第一個參數,是將要匹配的路由(模式)。` path()`方法使用尖括號,來定義將被捕獲、並作為命名參數傳遞給視圖函數的 URL 的部分。` re_path()`函數使用靈活的模式匹配方法,稱為正則表達式。我們將在後面的文章中討論這些內容! + +第二個參數,是在匹配模式時將調用的另一個函數。註釋 `views.book_detail`表示該函數名為`book_detail()`,可以在名為`views`的模塊中找到(即在名為`views.py`的文件中) + +### 處理請求(views.py) + +視圖是 Web 應用程序的核心,從 Web 客戶端接收 HTTP 請求並返回 HTTP 響應。在兩者之間,他們編制框架的其他資源來訪問數據庫,渲染模板等。 + +下面的例子顯示了一個最小的視圖功能 index(),這可以通過我們的 URL 映射器在上一節中調用。像所有視圖函數一樣,它接收一個 HttpRequest 對像作為參數(request)並返回一個 HttpResponse 對象。在這種情況下,我們對請求不做任何事情,我們的響應只是返回一個硬編碼的字符串。我們會向您顯示一個請求,在稍後的部分中會提供更有趣的內容。 + +```python +## filename: views.py (Django view functions) + +from django.http import HttpResponse + +def index(request): + # Get an HttpRequest - the request parameter + # perform operations using information from the request. + # Return HttpResponse + return HttpResponse('Hello from Django!') +``` + +> **備註:** 一點點 Python: +> +> - [Python 模塊](https://docs.python.org/3/tutorial/modules.html)是函數的“庫”,存放在單獨的文件中,我們可能希望在代碼中使用。在這裡,我們只導入了`HttpResponse`從對象`django.http`模塊,使我們可以在視圖中使用 +> `from django.http import HttpResponse`。 +> 還有其他方法可以從模塊導入一些或所有對象 +> - 使用`def`,如上所示的關鍵字聲明函數,命參數在函數名稱後面的括號中列出:整行以冒號結尾。注意下一行是否都**縮進**。縮進很重要,因為它指定代碼行在該特定塊內(強制縮進是 Python 的一個關鍵特徵,而且是 Python 代碼很容易閱讀的一個原因)。 + +視圖通常存放在一個名為**views.py**的文件中。 + +### 定義數據模型(models.py) + +Django Web 應用程序,通過被稱為模型的 Python 對象,來管理和查詢數據。模型定義存儲數據的結構,包括字段類型 以及字段可能的最大值,默認值,選擇列表選項,文檔幫助文本,表單的標籤文本等。模型的定義與底層數據庫無關-您可以選擇其中一個,作為項目設置的一部分。一旦您選擇了要使用的數據庫,您就不需要直接與之交談- 只需編寫模型結構和其他代碼,Django 可以處理與數據庫通信的所有辛苦的工作。 + +下面的代碼片段為`Team`對象,展示了一個非常簡單的 Django 模型。本`Team`類別是從 Django 的類別派生`models.Model`。它將團隊名稱和團隊級別,定義為字符字段,並為每個記錄指定了要存放的最大字符數。`team_level`可以是幾個值中的一個,因此,我們將其定義為一個選擇字段,並在被展示的數據、和被儲存的數據之間,建立映射,並設置一個默認值。 + +```python +# filename: models.py + +from django.db import models + +class Team(models.Model): + team_name = models.CharField(max_length=40) + + TEAM_LEVELS = ( + ('U09', 'Under 09s'), + ('U10', 'Under 10s'), + ('U11', 'Under 11s'), + ... #list other team levels + ) + team_level = models.CharField(max_length=3,choices=TEAM_LEVELS,default='U11') +``` + +> **備註:** Python 小知識: +> +> - Python 支持“面向對象編程”,這是一種編程風格,我們將代碼組織到對像中,其中包括用於對該對象進行操作的相關數據和功能。對像也可以從其他對象繼承/擴展/派生,允許相關對象之間的共同行為被共享。在 Python 中,我們使用關鍵字**Class**定義對象的“藍圖”。我們可以根據類中的模型創建類型的多個特定實例。 +> - 例如,我們有個**Team**類,它來自於**Model**類。這意味著它是一個模型,並且將包含模型的所有方法,但是我們也可以給它自己的專門功能。在我們的模型中,我們定義了我們的數據庫需要存儲我們的數據字段,給出它們的具體名稱。Django 使用這些定義(包括字段名稱)來創建底層數據庫。 + +### 查詢數據(views.py) + +Django 模型提供了一個,用於搜索數據庫的簡單查詢 API。這可以使用不同的標準(例如,精確,不區分大小寫,大於等等)來匹配多個字段,並且可以支持複雜語句(例如,您可以在擁有一個團隊的**U11**團隊上指定搜索名稱以“Fr ”開頭或以“al”結尾)。 + +代碼片段顯示了一個視圖函數(資源處理程序),用於顯示我們所有的**U09**團隊。**粗體**顯示如何使用模型查詢 API,過濾所有記錄,其中該 **team_level**字段,具有正確的文本“ **U09** ”(請注意,該條件如何 filter()作為參數傳遞給該函數,該字段名稱和匹配類型由雙下劃線: **team_level\_\_exact**) + +```python +## filename: views.py + +from django.shortcuts import render +from .models import Team + +def index(request): + list_teams = Team.objects.filter(team_level__exact="U09") + context = {'youngest_teams': list_teams} + return render(request, '/best/index.html', context) +``` + +此功能使用**render** ()功能創建**HttpResponse**發送回瀏覽器的功能。這個函數是一個快捷方式;它通過組合指定的 HTML 模版和一些數據來插入模版(在名為“ **content** ”的變量中提供)來創建一個**HTML**文件。在下一節中,我們將介紹如何在其中插入數據以創建**HTML**。 + +### 呈現數據(HTML 模版) + +模板系統允許您使用佔位符指定輸出文檔的結構,以便在生成頁面時填充數據。模板通常用於創建 HTML,但也可以創建其他類型的文檔。 Django 支持其本機模板系統,和另一個流行的 Python 庫,名為 Jinja2(如果需要,它也可以支持其他系統)。 + +代碼片段,顯示了上一節中`render()`函數調用的 HTML 模板的外觀。這個模板的編寫假設它在渲染時可以訪問名為`youngest_teams`的列表變量(包含在上面`render()`函數中的上下文變量`context`中)。在 HTML 框架內部,我們有一個表達式,首先檢查`youngest_teams`變量是否存在,然後在`for`循環中迭代它。在每次迭代中,模板在{{htmlelement("li")}}元素中顯示每個團隊的`team_name`值。 + +```python +## filename: best/templates/best/index.html + + + + + + {% if youngest_teams %} +
      + {% for team in youngest_teams %} +
    • \{\{ team.team_name \}\}
    • + {% endfor %} +
    +{% else %} +

    No teams are available.

    +{% endif %} + + + +``` + +## 你還能做什麼? + +前面的部分,展示了幾乎每個 Web 應用程序將使用的主要功能:URL 映射,視圖,模型和模版。Django 提供的其他內容包括: + +- **表單** : HTML 表單用於收集用戶數據,以便在服務器上進行處理。Django 簡化了表單創建,驗證和處理。 +- **用戶身份驗證和權限** : Django 包含了一個強大的用戶身份驗證和權限系統,該系統已經構建了安全性。 +- **緩存** :與提供靜態內容相比,動態創建內容需要更大的計算強度(也更緩慢)。Django 提供靈活的緩存,以便你可以存儲所有或部分的頁面。如無必要,不會重新呈現網頁。 +- **管理網站** :當你使用基本骨架創建應用時,就已經默認包含了一個 Django 管理站點。它十分輕鬆地創建了一個管理頁面,使網站管理員能夠創建、編輯和查看站點中的任何數據模型。 +- **序列化數據** : Django 可以輕鬆地將數據序列化,並支持 XML 或 JSON 格式。這會有助於創建一個 Web 服務(Web 服務指數據純粹為其他應用程序或站點所用,並不會在自己的站點中顯示),或是有助於創建一個由客戶端代碼處理、和呈現所有數據的網站。 + +## 總結 + +恭喜,您已經完成了 Django 之旅的第一步!您現在應該了解 Django 的主要優點,一些關於它的歷史,以及 Django 應用程序的每個主要部分可能是什麼樣子。您還應該了解 Python 編程語言的一些內容,包括列表,函數和類別的語法。 + +您已經看到上面的一些真正的 Django 代碼,但與客戶端代碼不同,您需要設置一個開發環境來運行它。這是我們的下一步。 + +{{NextMenu("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django")}} + +## 本教學連結 + +- [Django introduction](/en-US/docs/Learn/Server-side/Django/Introduction) +- [Setting up a Django development environment](/en-US/docs/Learn/Server-side/Django/development_environment) +- [Django Tutorial: The Local Library website](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django Tutorial Part 2: Creating a skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) +- [Django Tutorial Part 3: Using models](/en-US/docs/Learn/Server-side/Django/Models) +- [Django Tutorial Part 4: Django admin site](/en-US/docs/Learn/Server-side/Django/Admin_site) +- [Django Tutorial Part 5: Creating our home page](/en-US/docs/Learn/Server-side/Django/Home_page) +- [Django Tutorial Part 6: Generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views) +- [Django Tutorial Part 7: Sessions framework](/en-US/docs/Learn/Server-side/Django/Sessions) +- [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/Authentication) +- [Django Tutorial Part 9: Working with forms](/en-US/docs/Learn/Server-side/Django/Forms) +- [Django Tutorial Part 10: Testing a Django web application](/en-US/docs/Learn/Server-side/Django/Testing) +- [Django Tutorial Part 11: Deploying Django to production](/en-US/docs/Learn/Server-side/Django/Deployment) +- [Django web application security](/en-US/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django mini blog](/en-US/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/models/index.html b/files/zh-tw/learn/server-side/django/models/index.html deleted file mode 100644 index cdddf873b121f6..00000000000000 --- a/files/zh-tw/learn/server-side/django/models/index.html +++ /dev/null @@ -1,474 +0,0 @@ ---- -title: 'Django Tutorial Part 3: Using models' -slug: Learn/Server-side/Django/Models -translation_of: Learn/Server-side/Django/Models ---- -
    {{LearnSidebar}}
    - -
    {{PreviousMenuNext("Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django")}}
    - -

    - -

    本文介紹如何為 LocalLibrary 網站定義模型。它解釋了模型是什麼、聲明的方式以及一些主要字段類型。它還簡要展示了您可以訪問模型數據的幾個主要方法。

    - - - - - - - - - - - - -
    前提:Django 教學 2: 創建骨架網站。
    目標: -

    能夠設計和創建自己的模型,選擇適當的欄位。

    -
    - -

    概覽

    - -

    Django Web 應用程序通過被稱為模型的 Python 對象,訪問和管理數據。模型定義儲存數據的結構,包括欄位類型、以及可能還有最大大小,默認值,選擇列表選項,幫助文檔,表單的標籤文本等。模型的定義與底層數據庫無關 — 你可以選擇其中一個,作為項目設置的一部分。一旦你選擇了要使用的數據庫,你就不需要直接與之交談 — 只需編寫模型結構和其他代碼,Django 可以處理與數據庫通信的所有繁瑣工作。

    - -

    本教程將介紹如何定義和訪問 LocalLibrary 範例網站的模型。

    - -

    設計LocalLibrary模型

    - -

    在你投入開始編寫模型之前,花幾分鐘時間考慮我們需要存放的數據、以及不同物件之間的關係。

    - -

    我們知道,我們需要存放書籍的信息(標題,摘要,作者,語言,類別,ISBN),並且我們可能有多個副本(具有全域唯一的ID,可用狀態等)。我們可以存放更多關於作者的信息,而不僅僅是他的名字,或多個作者的相同或相似的名稱。我們希望能根據書名,作者名,語言和類別對信息進行排序。

    - -

    在設計模型時,為每個“物件”分別設置模型(相關信息分組)是有意義的。在這種情況下,明顯的物件是書籍,書本實例和作者。

    - -

    你可能想要使用模型,來表示選擇列表選項(例如:選擇下拉列表),而不是硬編碼,將選項編寫進網站—這是當所有選項面臨未知、或改變時候的建議。在本網站,模型的明顯候選,包括書籍類型(例如:科幻小說,法國詩歌等)和語言(英語,法語,日語)。

    - -

    一旦我們已經決定了我們的模型和字段,我們需要考慮它們的關聯性。Django允許你來定義一對一的關聯(OneToOneField),一對多(ForeignKey)和多對多(ManyToManyField)。

    - -

    思考一下,在網站中,我們將定義模型展示在下面UML關聯圖中(下圖)。如以上,我們創建了書的模型(書的通用細節),書本實例(系統中特定物理副本的書籍狀態),和作者。我們也決定了各類型模型,以便通過管理界面創建/選擇值。我們決定不給BookInstance:status一個模型 —我們硬編碼了(LOAN_STATUS)的值,因為我們不希望其改變。在每個框中,你可以看到模型名稱,字段名稱和類型,以及方法和返回類型。

    - -

    該圖顯示模型之間的關係,包括它們的多重性。多重性是圖中的數字,顯示可能存在於關係中的每個模型的數量(最大值和最小值)。例如,盒子之間的連接線,顯示書和類型相關。書模型中數字表明,一本書必須有一個或多個類型(想要多少就多少),而類型(Genres)模型線的另一端的數字(0..*),表明它可以有零個或多個關聯書本(可以有這個書籍類別,也有對應的書;也可以是有這個書籍類別,但沒有對應的書)。

    - -

    LocalLibrary Model UML

    - -
    -

    備註:下一節提供一個基本解釋模型的定義與使用,當你在讀的時候,也需要一邊考慮如何構建上圖中的每個模型。

    -
    - -

    模型入門

    - -

    本節簡要概述了模型定義,和一些重要的字段、和字段參數。

    - -

    模型定義

    - -

    模型通常在 app 中的 models.py 檔案中定義。它們是繼承自 django.db.models.Model的子類, 可以包括屬性,方法和描述性資料(metadata)。下面區段為一個名為MyModelName的「典型」模型範例碼:

    - -
    from django.db import models
    -
    -class MyModelName(models.Model):
    -    """A typical class defining a model, derived from the Model class."""
    -
    -    # Fields
    -    my_field_name = models.CharField(max_length=20, help_text='Enter field documentation')
    -    ...
    -
    -    # Metadata
    -    class Meta:
    -        ordering = ['-my_field_name']
    -
    -    # Methods
    -    def get_absolute_url(self):
    -         """Returns the url to access a particular instance of MyModelName."""
    -         return reverse('model-detail-view', args=[str(self.id)])
    -
    -    def __str__(self):
    -        """String for representing the MyModelName object (in Admin site etc.)."""
    -        return self.field_name
    - -

    在下面章節中,我們將更詳細解釋模型的每個功能。

    - -

    字段

    - -

    模型可以有任意數量的字段、任何類型的字段 — 每個字段都表示我們要存放在我們的一個資料庫中的一欄數據(a column of data)。每筆資料庫記錄(列 row)將由每個字段值之一組成。我們來看看上面看到的例子。

    - -
    my_field_name = models.CharField(max_length=20, help_text='Enter field documentation')
    - - - -

    在上面例子中,有個叫 my_field_name 的單一字段,其類型為 models.CharField — 這意味著這個字段將會包含字母、數字字符串。使用特定的類別分配字段類型,這些類別,決定了用於將數據存放在資料庫中的記錄的類型,以及從HTML表單接收到值(即構成有效值)時使用的驗證標準。字段類型還可以獲取參數,進一步指定字段如何存放或如何被使用。在這裡的情況下,我們給了字段兩個參數:

    - -
      -
    • max_length=20 — 表示此字段中值的最大長度為20個字符的狀態。
    • -
    • help_text="Enter field documentation" — 提供一個幫助用戶的文本標籤,讓用戶知道當前透過HTML表單輸入時要提供什麼值。
    • -
    - -

    字段名稱用於在視圖和模版中引用它。字段還有一個標籤,它被指定一個參數(verbose_name),或者通過大寫字段的變量名的第一個字母,並用空格替換下劃線(例如my_field_name 的默認標籤為 My field name )。

    - -

    如果模型在表單中呈現(例如:在管理站點中),則聲明該字段的順序,將影響其默認順序,但可能會被覆蓋。

    - -
    常用字段參數
    - -

    當聲明很多/大多數不同的字段類型時,可以使用以下常用參數:

    - -
      -
    • help_text :提供HTML表單文本標籤(eg i在管理站點中),如上所述。
    • -
    • verbose_name :字段標籤中的可讀性名稱,如果沒有被指定,Django將從字段名稱推斷默認的詳細名稱。
    • -
    • default :該字段的默認值。這可以是值或可呼叫物件(callable object),在這種情況下,每次創建新紀錄時都將呼叫該物件。
    • -
    • null:如為 True,即允許 Django 於資料庫該欄位寫入 NULL(但欄位型態如為 CharField 則會寫入空字串)。預設值是 False
    • -
    • blank :如果True,表單中的字段被允許為空白。默認是False,這意味著Django的表單驗證將強制你輸入一個值。這通常搭配 NULL=True 使用,因為如果要允許空值,你還希望數據庫能夠適當地表示它們。
    • -
    • choices :這是給此字段的一組選項。如果提供這一項,預設對應的表單部件是「該組選項的列表」,而不是原先的標准文本字段。
    • -
    • primary_key :如果是True,將當前字段設置為模型的主鍵(主鍵是被指定用來唯一辨識所有不同表記錄的特殊數據庫欄位(column))。如果沒有指定字段作為主鍵,則Django將自動為此添加一個字段。
    • -
    - -

    還有許多其他選項 — 你可以在這裡看到完整的字段選項

    - -
    常用字段類型
    - -

    以下列表描述了一些更常用的字段類型。

    - -
      -
    • CharField 是用來定義短到中等長度的字段字符串。你必須指定max_length要存儲的數據。
    • -
    • TextField 用於大型任意長度的字符串。你可以max_length為該字段指定一個字段,但僅當該字段以表單顯示時才會使用(不會在數據庫級別強制執行)。
    • -
    • IntegerField 是一個用於存儲整數(整數)值的字段,用於在表單中驗證輸入的值為整數。
    • -
    • DateFieldDateTimeField 用於存儲/表示日期和日期/時間信息(分別是Python.datetime.datedatetime.datetime 對象)。這些字段可以另外表明(互斥)參數 auto_now=Ture (在每次保存模型時將該字段設置為當前日期),auto_now_add(僅設置模型首次創建時的日期)和 default(設置默認日期,可以被用戶覆蓋)。
    • -
    • EmailField 用於存儲和驗證電子郵件地址。
    • -
    • FileFieldImageField 分別用於上傳文件和圖像(ImageField 只需添加上傳的文件是圖像的附加驗證)。這些參數用於定義上傳文件的存儲方式和位置。
    • -
    • AutoField 是一種 IntegerField 自動遞增的特殊類型。如果你沒有明確指定一個主鍵,則此類型的主鍵將自動添加到模型中。
    • -
    • ForeignKey 用於指定與另一個數據庫模型的一對多關係(例如,汽車有一個製造商,但製造商可以製作許多汽車)。關係的“一”側是包含密鑰的模型。
    • -
    • ManyToManyField 用於指定多對多關係(例如,一本書可以有幾種類型,每種類型可以包含幾本書)。在我們的圖書館應用程序中,我們將非常類似地使用它們 ForeignKeys,但是可以用更複雜的方式來描述組之間的關係。這些具有參數 on_delete 來定義關聯記錄被刪除時會發生什麼(例如,值 models.SET_NULL 將簡單地設置為值 NULL )。
    • -
    - -

    還有許多其他類型的字段,包括不同類型數字的字段(大整數,小整數,浮點數),布林值,URLs,唯一 ids 和其他 “時間相關” 的信息(持續時間,時間等)。你可以查閱完整列表 .

    - -

    - -

    元數據(Metadata)

    - -

    你可以通過宣告 class Meta 來宣告模型級別的元數據,如圖所示:

    - -
    class Meta:
    -    ordering = ['-my_field_name']
    -
    - -

    此元數據最有用的功能之一是控制在查詢模型類型時返回之記錄的默認排序。你可以透過在ordering 屬性的字段名稱列表中指定匹配順序來執行此操作,如上所示。排序將依賴字段的類型(字符串字段按字母順序排序,而日期字段按時間順序排序)。如上所示,你可以使用減號(-)前綴字段名稱以反轉排序順序。

    - -

    例如,如果我們選擇依照此預設來排列書單:

    - -
    ordering = ['title', '-pubdate']
    - -

    書單通過標題依據--字母排序--排列,從A到Z,然後再依每個標題的出版日期,從最新到最舊排列。

    - -

    另一個常見的屬性是 verbose_name ,一個 verbose_name 說明單數和複數形式的類別。

    - -
    verbose_name = 'BetterName'
    - -

    其他有用的屬性允許你為模型創建和應用新的“訪問權限”(預設權限會被自動套用),允許基於其他的字段排序,或聲明該類是”抽象的“(你無法創建的記錄基類,並將由其他型號派生)。

    - -

    許多其他元數據選項控制模型中必須使用哪些數據庫以及數據的存儲方式。(如果你需要模型映射一個現有數據庫,這會有用)。

    - -

    完整有用的元數據選項在這裡Model metadata options (Django docs).

    - -

    方法(Methods)

    - -

    一個模型也可以有方法。

    - -

    最起碼,在每個模型中,你應該定義標準的Python 類方法__str__() 來為每個物件返回一個人類可讀的字符串。此字符用於表示管理站點的各個記錄(以及你需要引用模型實例的任何其他位置)。通常這將返回模型中的標題或名稱字段。

    - -
    def __str__(self):
    -    return self.field_name
    - -

    Django 方法中另一個常用方法是 get_absolute_url() ,這函數返回一個在網站上顯示個人模型記錄的 URL(如果你定義了該方法,那麼 Django 將自動在“管理站點”中添加“在站點中查看“按鈕在模型的記錄編輯欄)。get_absolute_url()的典型示例如下:

    - -
    def get_absolute_url(self):
    -    """Returns the url to access a particular instance of the model."""
    -    return reverse('model-detail-view', args=[str(self.id)])
    -
    - -
    -

    注意 :假設你將使用URL/myapplication/mymodelname/2 來顯示模型的單個記錄(其中“2”是id特定記錄),則需要創建一個URL映射器來將響應和id傳遞給“模型詳細視圖” (這將做出顯示記錄所需的工作)。以上示例中,reverse()函數可以“反轉”你的url映射器(在上訴命名為“model-detail-view”的案例中,以創建正確格式的URL。

    - -

    當然要做這個工作,你還是要寫URL映射,視圖和模版!

    -
    - -

    你可以定義一些你喜歡的其他方法,並從你的代碼或模版調用它們(只要它們不帶任何參數)。

    - -

    模型管理

    - -

    一旦你定義了模型類,你可以使用它們來創建,更新或刪除記錄,並運行查詢獲取所有記錄或特定的記錄子集。當我們定義我們的視圖,我們將展示給你在這個教程如何去做。

    - -

    創建和修改記錄

    - -

    要創建一個記錄,你可以定義一個模型實例,然後呼叫 save()

    - -
    # Create a new record using the model's constructor.
    -record = MyModelName(my_field_name="Instance #1")
    -
    -# Save the object into the database.
    -record.save()
    - -
    -

    註:如果沒有任何的欄位被宣告為主鍵,這筆新的紀錄會被自動的賦予一個主鍵並將主鍵欄命名為 id。上例的那筆資料被儲存後,試著查詢這筆紀錄會看到它被自動賦予 1 的編號。

    -
    - -

    你可以透過「點(dot)的語法」取得或變更這筆新資料的欄位(字段)。你需要呼叫 save() 將變更過的資料存進資料庫。

    - -
    # Access model field values using Python attributes.
    -print(record.id) #should return 1 for the first record.
    -print(record.my_field_name) # should print 'Instance #1'
    -
    -# Change record by modifying the fields, then calling save().
    -record.my_field_name = "New Instance Name"
    -record.save()
    -
    - -

    搜尋紀錄

    - -

    你可以使用模型的 objects 屬性(由 base class 提供)搜尋符合某個條件的紀錄。You can search for records that match a certain criteria using the model's attribute (provided by the base class).

    - -
    -

    Note: 要用"抽象的"模型還有欄位說明怎麼搜尋紀錄可能會有點令人困惑。我們會以一個Book模型,其包含titlegenre字段,而genre 也是一個僅有name一個字段的模型。

    -
    - -

    我們可以取得一個模型的所有紀錄,為一個 QuerySet 使用objects.all()。 QuerySet 是一個可迭代的物件,表示他含有多個物件,而我們可以藉由迭代/迴圈取得每個物件。

    - -
    all_books = Book.objects.all()
    -
    - -

    Django的 filter() 方法讓我們可以透過符合特定文字或數值的字段篩選回傳的QuerySet。例如篩選書名裡有 "wild" 的書並且計算總數,如下面所示。

    - -
    wild_books = Book.objects.filter(title__contains='wild')
    -number_wild_books = Book.objects.filter(title__contains='wild').count()
    -
    - -

    要比對的字段與比對方法都要被定義在篩選的參數名稱裡,並且使用這個格式:比對字段__比對方法 (請注意上方範例中的 titlecontains 中間隔了兩個底線唷)。在上面我們使用大小寫區分的方式比對title 。還有很多比對方式可以使用: icontains (不區分大小寫), iexact (大小寫區分且完全符合), exact (不區分大小寫但完全符合) 還有 in, gt (大於), startswith, 之類的。全部的用法在這裡。

    - -

    有時候你會須要透過某個一對多的字段來篩選(例如一個 外鍵)。 這樣的狀況下,你可以使用兩個底線來指定相關模型的字段。例如透過某個特定的genre名稱篩選書籍,如下所示:

    - -
    # 會比對到: Fiction, Science fiction, non-fiction etc.
    -books_containing_genre = Book.objects.filter(genre__name__icontains='fiction')
    -
    - -
    -

    Note: 你可隨心地使用雙底線 (__) 來探索更多層的關係 (ForeignKey/ManyToManyField). 例如, 一本 Book 有許多不同的 types, 其進一步定義有參數 name 關聯的"cover":type__cover__name__exact='hard'.

    -
    - -

    還有很多是你可以用索引(queries)來做的,包含從相關的模型做向後查詢(backwards searches)、連鎖過濾器(chaining filters)、回傳「值的小集合」等。更多資訊可以到 Making queries (Django Docs) 查詢。

    - -

    定義 LocalLibrary 模型

    - -

    這部份我們會開始定義圖書館的模型。

    - -

    先打開 models.py (在 /locallibrary/catalog/),頁面的最上方可以看到樣板導入了 models 模組,其包含了模型的基本類別 models.Model ,能使我們的模型能夠繼承。

    - -
    from django.db import models
    -
    -# Create your models here.
    - -

    書籍類型模型 (Genre model)

    - -

    複製下方 Genre 模型的程式碼,並貼在你的 models.py 檔案底部,這個模型是用來儲存書籍類型的資訊 — 例如:該本書是否為科幻小說、羅曼史、軍事歷史等。

    - -

    就像先前提到的,我們以「模型」的方式建立一個書籍類型模型,而非以自由文本(free text)或者選擇列表(selection list)的方式,這樣做讓我們可以透過資料庫的形式而非硬編碼(hard coded)的方式來管理所有可能的值。

    - -
    class Genre(models.Model):
    -    """Model representing a book genre."""
    -    name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)')
    -
    -    def __str__(self):
    -        """String for representing the Model object."""
    -        return self.name
    - -

    此模型有一個單一的 CharField 字段(name) 被用來描述書籍類別(限制輸入字元長度最多200個,同時也有提示文本(help_text) )。

    - -

    在模型最下方我們宣告一個 __str__() 方法來簡單回傳被特定一筆紀錄定義的書籍類別名稱。

    - -

    因為詳細名稱(verbose name)沒有被定義,所以字段在形式上會被稱為 Name

    - -

    書本模型 (Book model)

    - -

    複製下方 Book 模型的程式碼,並貼在你的 models.py 檔案底部,這個 Book 模型一般來說代表一個可用書本的所有資訊,但並非包含特定的物理實例(physical instance)或者副本資訊(copy),此模型使用 CharField 來表示書的 titleisbn (國際標準書號)(note how the isbn specifies its label as "ISBN" using the first unnamed parameter because the default label would otherwise be "Isbn").,另外此模型使用 TextField 來存 summary ,因為此文本可能會很長。

    - -
    from django.urls import reverse #Used to generate URLs by reversing the URL patterns
    -
    -class Book(models.Model):
    -    """Model representing a book (but not a specific copy of a book)."""
    -    title = models.CharField(max_length=200)
    -    author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
    -
    -    # Foreign Key used because book can only have one author, but authors can have multiple books
    -    # Author as a string rather than object because it hasn't been declared yet in the file.
    -    summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book')
    -    isbn = models.CharField('ISBN', max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')
    -
    -    # ManyToManyField used because genre can contain many books. Books can cover many genres.
    -    # Genre class has already been defined so we can specify the object above.
    -    genre = models.ManyToManyField(Genre, help_text='Select a genre for this book')
    -
    -    def __str__(self):
    -        """String for representing the Model object."""
    -        return self.title
    -
    -    def get_absolute_url(self):
    -        """Returns the url to access a detail record for this book."""
    -        return reverse('book-detail', args=[str(self.id)])
    -
    -
    - -

    「書籍類別」(genre)是一個 ManyToManyField ,因此一本書可以有很多書籍類別,而一個書結類別也能夠對應到很多本書。作者(author)被宣告為外鍵(ForeignKey),因此每本書只會有一名作者,但一名作者可能會有多本書(實際上,一本書可能會有多名作者,不過這個案例不會有,所以在別的例子這種作法可能會有問題)

    - -

    在上面兩個宣告關聯性模型的敘述句內,關聯的對象都是用對象的模型類或字串的方式作為首個未具名參數的方式傳入句內做宣告。在關聯對象尚未被定義前,若要參照到該對象,必須使用該對象名稱字串的方式來宣告關聯性!還有一些 author 欄位的其它值得一提的參數:null=True 表示如果沒有作者的話,允許在資料庫中存入 Null 值;on_delete=models.SET_NULL 表示如果某筆作者紀錄被刪除的話,與該作者相關連的欄位都會被設成 Null

    - -

    這個模型也定義了 __str__() ,使用書本的 title 字段來表示一筆 Book 的紀錄。而最後一個方法,get_absolute_url() ,則會回傳一個可以被用來存取該模型細節紀錄的 URL (要讓其有效運作,我們必須定義一個 URL 的映射,我們將其命名為 book-detail ,另外還得定義一個關聯示圖(view)與模板(template) )。

    - -

    書本詳情模型 (BookInstance model)

    - -

    接下來,複製下方 BookInstance 的模型,貼在其他模型下面,這個 BookInstance 模型表示一個特定的書籍副本(可會被某人借走),並且包含如「副本是否可用」、「預計歸還日期」、「版本說明」或「版本細節」等資訊,還有一個在圖書館中唯一的 id 。

    - -

    有些字段(fields)和方法(methods)現在你也熟悉了。此模型使用了:

    - -
      -
    • ForeignKey 用來辨識相關的 Book (每本書可以有很多副本,但每個副本只能有一個Book)
    • -
    • CharField 用來表示該本書的版本說明(特定版本)
    • -
    - -
    import uuid # Required for unique book instances
    -
    -class BookInstance(models.Model):
    -    """Model representing a specific copy of a book (i.e. that can be borrowed from the library)."""
    -    id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library')
    -    book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True)
    -    imprint = models.CharField(max_length=200)
    -    due_back = models.DateField(null=True, blank=True)
    -
    -    LOAN_STATUS = (
    -        ('m', 'Maintenance'),
    -        ('o', 'On loan'),
    -        ('a', 'Available'),
    -        ('r', 'Reserved'),
    -    )
    -
    -    status = models.CharField(
    -        max_length=1,
    -        choices=LOAN_STATUS,
    -        blank=True,
    -        default='m',
    -        help_text='Book availability',
    -    )
    -
    -    class Meta:
    -        ordering = ['due_back']
    -
    -    def __str__(self):
    -        """String for representing the Model object."""
    -        return f'{self.id} ({self.book.title})'
    - -

    我們額外宣告了一些新的字段(field)類別(types):

    - -
      -
    • UUIDField 被用來將 id 字段再這個模型中設定為 primary_key ,這類別的字段會分配一個全域唯一的值給每一個實例(instance),也就是任何一本你能在圖書館找到的書。
    • -
    • DateField 會被用來設定 due_back 的日期(紀錄書本何時會被歸還,可再被使用,或者是否正在保養期),這個字段允許 blanknull 值,而當元數據模型 (Class Meta)收到請求(query)時也會使用此字段來做資料排序。
    • -
    • status 是一個 CharField 字段,用來定義一個選項列表。你可以看到,我們定義了一個包含「鍵-值對元組」的元組(tuple) 並使其成為選項的參數,鍵-值對中的值會陳列出來並可以被使用者選擇,當選項被選定後,鍵(key)也會被儲存下來。我們也設定了預設的鍵值為 "m" (maintenance) 用來表示當每本書在初始創造還未放上書架時是不可被使用的。
    • -
    - -

    __str__() 模型用來表示 BookInstance 這個物件的「唯一 ID」和「相關之 Book 書本名稱(title)」的組合。

    - -
    -

    Note: 關於 Python 的小提醒:

    - -
      -
    • 從 Python3.6 開始,你可以使用「字串插值語法」(又稱做 f-string):
      - f'{self.id} ({self.book.title})'
    • -
    • 在舊版 Python 這部分的教學中,我們則使用了另一種有效的 formatted string 語法
      - (e.g. '{0} ({1})'.format(self.id,self.book.title))
    • -
    -
    - -

    作者模型(Author model)

    - -

    複製下方 Author 的模型程式碼並貼在 models.py 文件的最下方。

    - -

    現在所有的字段(fields)與方法(methods)你應該都熟悉了,此模型定義了作者的「名」、「姓」、「出生年月日」、「死亡日期(非必填)」。該模型也指定,預設情況下,__str__() 方法會回傳作者姓名(按照姓、名排序)。而 get_absolute_url() 方法會反轉 author-detail 的URL映射,來獲得顯示單個作者的URL。

    - -
    class Author(models.Model):
    -    """Model representing an author."""
    -    first_name = models.CharField(max_length=100)
    -    last_name = models.CharField(max_length=100)
    -    date_of_birth = models.DateField(null=True, blank=True)
    -    date_of_death = models.DateField('Died', null=True, blank=True)
    -
    -    class Meta:
    -        ordering = ['last_name', 'first_name']
    -
    -    def get_absolute_url(self):
    -        """Returns the url to access a particular author instance."""
    -        return reverse('author-detail', args=[str(self.id)])
    -
    -    def __str__(self):
    -        """String for representing the Model object."""
    -        return f'{self.last_name}, {self.first_name}'
    -
    -
    - -

    再次執行資料庫遷移(database migrations)

    - -

    你的所有模型都建立好了,現在必須再次執行你的資料庫 migrations 指令來將這些修改內容更信到資料庫中。

    - -
    python3 manage.py makemigrations
    -python3 manage.py migrate
    - -

    語言模型(Language model) — 挑戰

    - -

    請想像一下,現在來了一位善心人士捐了一堆用不同語言寫的書(例如:波斯語),而你的挑戰是必須制定一個最好在我們的圖說館網站呈現的方式,並把它做成模組。

    - -

    幾件事情需要思考:

    - -
      -
    • 「語言」需要與 BookBookInstance 或其他物件(Object)相關聯嗎?
    • -
    • 「不同語言」能以什麼形式來表示?
      - 模型?自由文本字段(free text field)?硬編碼選擇列表(hard-coded selection list)?
    • -
    - -

    當你決定好了,就開始動手吧!你可以在Github的這裡看到我們是怎麼思考的。

    - -
      -
    - -
      -
    - -

    小結

    - -

    在這篇文章我們學到如何定義模型,並且利用這些資訊來設計與實作適合的模型給 LocalLibrary 網站。

    - -

    再來我們要稍微撇開建立網站,先來看看 Django 的管理站(Django Administration site),這個管理站能讓我們加入一些資料到圖書館中,讓我們再來能夠透過「示圖(views)與模板(templates)」(當然我們現在都還沒建立)來展示。

    - -

    延伸閱讀

    - - - -

    {{PreviousMenuNext("Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django")}}

    - -

    In this module

    - - diff --git a/files/zh-tw/learn/server-side/django/models/index.md b/files/zh-tw/learn/server-side/django/models/index.md new file mode 100644 index 00000000000000..253db32f78624c --- /dev/null +++ b/files/zh-tw/learn/server-side/django/models/index.md @@ -0,0 +1,450 @@ +--- +title: 'Django Tutorial Part 3: Using models' +slug: Learn/Server-side/Django/Models +translation_of: Learn/Server-side/Django/Models +--- +{{LearnSidebar}}{{PreviousMenuNext("Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django")}} + +本文介紹如何為 [LocalLibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) 網站定義模型。它解釋了模型是什麼、聲明的方式以及一些主要字段類型。它還簡要展示了您可以訪問模型數據的幾個主要方法。 + + + + + + + + + + + + +
    前提: + Django 教學 2: 創建骨架網站。 +
    目標:

    能夠設計和創建自己的模型,選擇適當的欄位。

    + +## 概覽 + +Django Web 應用程序通過被稱為模型的 Python 對象,訪問和管理數據。模型定義儲存數據的結構,包括欄位類型、以及可能還有最大大小,默認值,選擇列表選項,幫助文檔,表單的標籤文本等。模型的定義與底層數據庫無關 — 你可以選擇其中一個,作為項目設置的一部分。一旦你選擇了要使用的數據庫,你就不需要直接與之交談 — 只需編寫模型結構和其他代碼,Django 可以處理與數據庫通信的所有繁瑣工作。 + +本教程將介紹如何定義和訪問 [LocalLibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) 範例網站的模型。 + +## 設計 LocalLibrary 模型 + +在你投入開始編寫模型之前,花幾分鐘時間考慮我們需要存放的數據、以及不同物件之間的關係。 + +我們知道,我們需要存放書籍的信息(標題,摘要,作者,語言,類別,ISBN),並且我們可能有多個副本(具有全域唯一的 ID,可用狀態等)。我們可以存放更多關於作者的信息,而不僅僅是他的名字,或多個作者的相同或相似的名稱。我們希望能根據書名,作者名,語言和類別對信息進行排序。 + +在設計模型時,為每個“物件”分別設置模型(相關信息分組)是有意義的。在這種情況下,明顯的物件是書籍,書本實例和作者。 + +你可能想要使用模型,來表示選擇列表選項(例如:選擇下拉列表),而不是硬編碼,將選項編寫進網站—這是當所有選項面臨未知、或改變時候的建議。在本網站,模型的明顯候選,包括書籍類型(例如:科幻小說,法國詩歌等)和語言(英語,法語,日語)。 + +一旦我們已經決定了我們的模型和字段,我們需要考慮它們的關聯性。Django 允許你來定義一對一的關聯(`OneToOneField`),一對多(`ForeignKey`)和多對多(`ManyToManyField`)。 + +思考一下,在網站中,我們將定義模型展示在下面 UML 關聯圖中(下圖)。如以上,我們創建了書的模型(書的通用細節),書本實例(系統中特定物理副本的書籍狀態),和作者。我們也決定了各類型模型,以便通過管理界面創建/選擇值。我們決定不給`BookInstance:status`一個模型 —我們硬編碼了(`LOAN_STATUS`)的值,因為我們不希望其改變。在每個框中,你可以看到模型名稱,字段名稱和類型,以及方法和返回類型。 + +該圖顯示模型之間的關係,包括它們的多重性。多重性是圖中的數字,顯示可能存在於關係中的每個模型的數量(最大值和最小值)。例如,盒子之間的連接線,顯示書和類型相關。書模型中數字表明,一本書必須有一個或多個類型(想要多少就多少),而類型(Genres)模型線的另一端的數字(0..\*),表明它可以有零個或多個關聯書本(可以有這個書籍類別,也有對應的書;也可以是有這個書籍類別,但沒有對應的書)。 + +![LocalLibrary Model UML](local_library_model_uml.svg) + +> **備註:** 下一節提供一個基本解釋模型的定義與使用,當你在讀的時候,也需要一邊考慮如何構建上圖中的每個模型。 + +## 模型入門 + +本節簡要概述了模型定義,和一些重要的字段、和字段參數。 + +### 模型定義 + +模型通常在 app 中的 **models.py** 檔案中定義。它們是繼承自 `django.db.models.Model`的子類, 可以包括屬性,方法和描述性資料(metadata)。下面區段為一個名為`MyModelName`的「典型」模型範例碼: + + from django.db import models + + class MyModelName(models.Model): + """A typical class defining a model, derived from the Model class.""" + + # Fields + my_field_name = models.CharField(max_length=20, help_text='Enter field documentation') + ... + + # Metadata + class Meta: + ordering = ['-my_field_name'] + + # Methods + def get_absolute_url(self): + """Returns the url to access a particular instance of MyModelName.""" + return reverse('model-detail-view', args=[str(self.id)]) + + def __str__(self): + """String for representing the MyModelName object (in Admin site etc.).""" + return self.field_name + +在下面章節中,我們將更詳細解釋模型的每個功能。 + +#### 字段 + +模型可以有任意數量的字段、任何類型的字段 — 每個字段都表示我們要存放在我們的一個資料庫中的一欄數據(a column of data)。每筆資料庫記錄(列 row)將由每個字段值之一組成。我們來看看上面看到的例子。 + + my_field_name = models.CharField(max_length=20, help_text='Enter field documentation') + +在上面例子中,有個叫 `my_field_name` 的單一字段,其類型為 `models.CharField` — 這意味著這個字段將會包含字母、數字字符串。使用特定的類別分配字段類型,這些類別,決定了用於將數據存放在資料庫中的記錄的類型,以及從 HTML 表單接收到值(即構成有效值)時使用的驗證標準。字段類型還可以獲取參數,進一步指定字段如何存放或如何被使用。在這裡的情況下,我們給了字段兩個參數: + +- `max_length=20` — 表示此字段中值的最大長度為 20 個字符的狀態。 +- `help_text="Enter field documentation"` — 提供一個幫助用戶的文本標籤,讓用戶知道當前透過 HTML 表單輸入時要提供什麼值。 + +字段名稱用於在視圖和模版中引用它。字段還有一個標籤,它被指定一個參數(`verbose_name`),或者通過大寫字段的變量名的第一個字母,並用空格替換下劃線(例如`my_field_name` 的默認標籤為 My field name )。 + +如果模型在表單中呈現(例如:在管理站點中),則聲明該字段的順序,將影響其默認順序,但可能會被覆蓋。 + +##### 常用字段參數 + +當聲明很多/大多數不同的字段類型時,可以使用以下常用參數: + +- [help_text](https://docs.djangoproject.com/en/1.10/ref/models/fields/#help-text) :提供 HTML 表單文本標籤(eg i 在管理站點中),如上所述。 +- [verbose_name](https://docs.djangoproject.com/en/1.10/ref/models/fields/#verbose-name) :字段標籤中的可讀性名稱,如果沒有被指定,Django 將從字段名稱推斷默認的詳細名稱。 +- [default](https://docs.djangoproject.com/en/1.10/ref/models/fields/#default) :該字段的默認值。這可以是值或可呼叫物件(callable object),在這種情況下,每次創建新紀錄時都將呼叫該物件。 +- [null](https://docs.djangoproject.com/en/1.10/ref/models/fields/#null):如為 `True`,即允許 Django 於資料庫該欄位寫入 `NULL`(但欄位型態如為 `CharField` 則會寫入空字串)。預設值是 `False`。 +- [blank](https://docs.djangoproject.com/en/1.10/ref/models/fields/#blank) :如果**`True`**,表單中的字段被允許為空白。默認是`False`,這意味著 Django 的表單驗證將強制你輸入一個值。這通常搭配 `NULL=True` 使用,因為如果要允許空值,你還希望數據庫能夠適當地表示它們。 +- [choices](https://docs.djangoproject.com/en/1.10/ref/models/fields/#choices) :這是給此字段的一組選項。如果提供這一項,預設對應的表單部件是「該組選項的列表」,而不是原先的標准文本字段。 +- [primary_key](https://docs.djangoproject.com/en/1.10/ref/models/fields/#primary-key) :如果是 True,將當前字段設置為模型的主鍵(主鍵是被指定用來唯一辨識所有不同表記錄的特殊數據庫欄位(column))。如果沒有指定字段作為主鍵,則 Django 將自動為此添加一個字段。 + +還有許多其他選項 — 你可以在[這裡看到完整的字段選項](https://docs.djangoproject.com/en/1.10/ref/models/fields/#field-options)。 + +##### 常用字段類型 + +以下列表描述了一些更常用的字段類型。 + +- [CharField](https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.CharField) 是用來定義短到中等長度的字段字符串。你必須指定`max_length`要存儲的數據。 +- [TextField ](https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.TextField)用於大型任意長度的字符串。你可以`max_length`為該字段指定一個字段,但僅當該字段以表單顯示時才會使用(不會在數據庫級別強制執行)。 +- [IntegerField](https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.IntegerField) 是一個用於存儲整數(整數)值的字段,用於在表單中驗證輸入的值為整數。 +- [DateField](https://docs.djangoproject.com/en/1.10/ref/models/fields/#datefield) 和[DateTimeField](https://docs.djangoproject.com/en/1.10/ref/models/fields/#datetimefield) 用於存儲/表示日期和日期/時間信息(分別是`Python.datetime.date` 和 `datetime.datetime` 對象)。這些字段可以另外表明(互斥)參數 `auto_now=Ture` (在每次保存模型時將該字段設置為當前日期),`auto_now_add`(僅設置模型首次創建時的日期)和 `default`(設置默認日期,可以被用戶覆蓋)。 +- [EmailField](https://docs.djangoproject.com/en/1.10/ref/models/fields/#emailfield) 用於存儲和驗證電子郵件地址。 +- [FileField](https://docs.djangoproject.com/en/1.10/ref/models/fields/#filefield) 和[ImageField](https://docs.djangoproject.com/en/1.10/ref/models/fields/#imagefield) 分別用於上傳文件和圖像(`ImageField` 只需添加上傳的文件是圖像的附加驗證)。這些參數用於定義上傳文件的存儲方式和位置。 +- [AutoField](https://docs.djangoproject.com/en/1.10/ref/models/fields/#autofield) 是一種 **IntegerField** 自動遞增的特殊類型。如果你沒有明確指定一個主鍵,則此類型的主鍵將自動添加到模型中。 +- [ForeignKey](https://docs.djangoproject.com/en/1.10/ref/models/fields/#foreignkey) 用於指定與另一個數據庫模型的一對多關係(例如,汽車有一個製造商,但製造商可以製作許多汽車)。關係的“一”側是包含密鑰的模型。 +- [ManyToManyField](https://docs.djangoproject.com/en/1.10/ref/models/fields/#manytomanyfield) 用於指定[多對多](https://docs.djangoproject.com/en/1.10/ref/models/fields/#manytomanyfield)關係(例如,一本書可以有幾種類型,每種類型可以包含幾本書)。在我們的圖書館應用程序中,我們將非常類似地使用它們 ForeignKeys,但是可以用更複雜的方式來描述組之間的關係。這些具有參數 `on_delete` 來定義關聯記錄被刪除時會發生什麼(例如,值 `models.SET_NULL` 將簡單地設置為值 NULL )。 + +還有許多其他類型的字段,包括不同類型數字的字段(大整數,小整數,浮點數),布林值,URLs,唯一 ids 和其他 “時間相關” 的信息(持續時間,時間等)。你可以查閱[完整列表](https://docs.djangoproject.com/en/1.10/ref/models/fields/#field-types) . + +#### 元數據(Metadata) + +你可以通過宣告 class Meta 來宣告模型級別的元數據,如圖所示: + +```python +class Meta: + ordering = ['-my_field_name'] +``` + +此元數據最有用的功能之一是控制在查詢模型類型時返回之記錄的默認排序。你可以透過在`ordering` 屬性的字段名稱列表中指定匹配順序來執行此操作,如上所示。排序將依賴字段的類型(字符串字段按字母順序排序,而日期字段按時間順序排序)。如上所示,你可以使用減號(-)前綴字段名稱以反轉排序順序。 + +例如,如果我們選擇依照此預設來排列書單: + +```python +ordering = ['title', '-pubdate'] +``` + +書單通過標題依據--字母排序--排列,從 A 到 Z,然後再依每個標題的出版日期,從最新到最舊排列。 + +另一個常見的屬性是 `verbose_name` ,一個 `verbose_name` 說明單數和複數形式的類別。 + +```python +verbose_name = 'BetterName' +``` + +其他有用的屬性允許你為模型創建和應用新的“訪問權限”(預設權限會被自動套用),允許基於其他的字段排序,或聲明該類是”抽象的“(你無法創建的記錄基類,並將由其他型號派生)。 + +許多其他元數據選項控制模型中必須使用哪些數據庫以及數據的存儲方式。(如果你需要模型映射一個現有數據庫,這會有用)。 + +完整有用的元數據選項在這裡[Model metadata options](https://docs.djangoproject.com/en/1.10/ref/models/options/) (Django docs). + +#### 方法(Methods) + +一個模型也可以有方法。 + +**最起碼,在每個模型中,你應該定義標準的 Python 類方法`__str__()` **,**來為每個物件返回一個人類可讀的字符串**。此字符用於表示管理站點的各個記錄(以及你需要引用模型實例的任何其他位置)。通常這將返回模型中的標題或名稱字段。 + +```python +def __str__(self): + return self.field_name +``` + +Django 方法中另一個常用方法是 `get_absolute_url()` ,這函數返回一個在網站上顯示個人模型記錄的 URL(如果你定義了該方法,那麼 Django 將自動在“管理站點”中添加“在站點中查看“按鈕在模型的記錄編輯欄)。`get_absolute_url()`的典型示例如下: + +```python +def get_absolute_url(self): + """Returns the url to access a particular instance of the model.""" + return reverse('model-detail-view', args=[str(self.id)]) +``` + +> **備註:** 假設你將使用 URL`/myapplication/mymodelname/2` 來顯示模型的單個記錄(其中“2”是 id 特定記錄),則需要創建一個 URL 映射器來將響應和 id 傳遞給“模型詳細視圖” (這將做出顯示記錄所需的工作)。以上示例中,`reverse()`函數可以“反轉”你的 url 映射器(在上訴命名為“model-detail-view”的案例中,以創建正確格式的 URL。 +> +> 當然要做這個工作,你還是要寫 URL 映射,視圖和模版! + +你可以定義一些你喜歡的其他方法,並從你的代碼或模版調用它們(只要它們不帶任何參數)。 + +### 模型管理 + +一旦你定義了模型類,你可以使用它們來創建,更新或刪除記錄,並運行查詢獲取所有記錄或特定的記錄子集。當我們定義我們的視圖,我們將展示給你在這個教程如何去做。 + +#### 創建和修改記錄 + +要創建一個記錄,你可以定義一個模型實例,然後呼叫 `save()`。 + +```python +# Create a new record using the model's constructor. +record = MyModelName(my_field_name="Instance #1") + +# Save the object into the database. +record.save() +``` + +> **備註:** 如果沒有任何的欄位被宣告為`主鍵`,這筆新的紀錄會被自動的賦予一個主鍵並將主鍵欄命名為 `id`。上例的那筆資料被儲存後,試著查詢這筆紀錄會看到它被自動賦予 1 的編號。 + +你可以透過「點(dot)的語法」取得或變更這筆新資料的欄位(字段)。你需要呼叫 `save()` 將變更過的資料存進資料庫。 + +```python +# Access model field values using Python attributes. +print(record.id) #should return 1 for the first record. +print(record.my_field_name) # should print 'Instance #1' + +# Change record by modifying the fields, then calling save(). +record.my_field_name = "New Instance Name" +record.save() +``` + +#### 搜尋紀錄 + +你可以使用模型的 `objects` 屬性(由 base class 提供)搜尋符合某個條件的紀錄。You can search for records that match a certain criteria using the model's attribute (provided by the base class). + +> **備註:** 要用"抽象的"模型還有欄位說明怎麼搜尋紀錄可能會有點令人困惑。我們會以一個 Book 模型,其包含`title`與`genre`字段,而 genre 也是一個僅有`name`一個字段的模型。 + +我們可以取得一個模型的所有紀錄,為一個 `QuerySet` 使用`objects.all()。` `QuerySet` 是一個可迭代的物件,表示他含有多個物件,而我們可以藉由迭代/迴圈取得每個物件。 + +```python +all_books = Book.objects.all() +``` + +Django 的 `filter()` 方法讓我們可以透過符合特定文字或數值的字段篩選回傳的`QuerySet`。例如篩選書名裡有 "wild" 的書並且計算總數,如下面所示。 + +```python +wild_books = Book.objects.filter(title__contains='wild') +number_wild_books = Book.objects.filter(title__contains='wild').count() +``` + +要比對的字段與比對方法都要被定義在篩選的參數名稱裡,並且使用這個格式:`比對字段__比對方法` (請注意上方範例中的 `title` 與 `contains` 中間隔了兩個底線唷)。在上面我們使用大小寫區分的方式比對`title` 。還有很多比對方式可以使用: `icontains` (不區分大小寫), `iexact` (大小寫區分且完全符合), `exact` (不區分大小寫但完全符合) 還有 `in`, `gt` (大於), `startswith`, 之類的。[全部的用法在這裡。](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#field-lookups) + +有時候你會須要透過某個一對多的字段來篩選(例如一個 `外鍵`)。 這樣的狀況下,你可以使用兩個底線來指定相關模型的字段。例如透過某個特定的 genre 名稱篩選書籍,如下所示: + +```python +# 會比對到: Fiction, Science fiction, non-fiction etc. +books_containing_genre = Book.objects.filter(genre__name__icontains='fiction') +``` + +> **備註:** 你可隨心地使用雙底線 (\_\_) 來探索更多層的關係 (`ForeignKey`/`ManyToManyField`). 例如, 一本 `Book` 有許多不同的 types, 其進一步定義有參數 name 關聯的"cover":`type__cover__name__exact='hard'.` + +還有很多是你可以用索引(queries)來做的,包含從相關的模型做向後查詢(backwards searches)、連鎖過濾器(chaining filters)、回傳「值的小集合」等。更多資訊可以到 [Making queries](https://docs.djangoproject.com/en/2.0/topics/db/queries/) (Django Docs) 查詢。 + +## 定義 LocalLibrary 模型 + +這部份我們會開始定義圖書館的模型。 + +先打開 models.py (在 _/locallibrary/catalog/_),頁面的最上方可以看到樣板導入了 models 模組,其包含了模型的基本類別 `models.Model` ,能使我們的模型能夠繼承。 + +```python +from django.db import models + +# Create your models here. +``` + +### 書籍類型模型 (Genre model) + +複製下方 `Genre` 模型的程式碼,並貼在你的 `models.py` 檔案底部,這個模型是用來儲存書籍類型的資訊 — 例如:該本書是否為科幻小說、羅曼史、軍事歷史等。 + +就像先前提到的,我們以「模型」的方式建立一個書籍類型模型,而非以自由文本(free text)或者選擇列表(selection list)的方式,這樣做讓我們可以透過資料庫的形式而非硬編碼(hard coded)的方式來管理所有可能的值。 + +```python +class Genre(models.Model): + """Model representing a book genre.""" + name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)') + + def __str__(self): + """String for representing the Model object.""" + return self.name +``` + +此模型有一個單一的 `CharField` 字段(`name`) 被用來描述書籍類別(限制輸入字元長度最多 200 個,同時也有提示文本(help_text) )。 + +在模型最下方我們宣告一個 `__str__()` 方法來簡單回傳被特定一筆紀錄定義的書籍類別名稱。 + +因為詳細名稱(verbose name)沒有被定義,所以字段在形式上會被稱為 `Name` 。 + +### 書本模型 (Book model) + +複製下方 Book 模型的程式碼,並貼在你的 `models.py` 檔案底部,這個 `Book` 模型一般來說代表一個可用書本的所有資訊,但並非包含特定的物理實例(physical instance)或者副本資訊(copy),此模型使用 `CharField` 來表示書的 `title` 和 `isbn` (國際標準書號)(note how the `isbn` specifies its label as "ISBN" using the first unnamed parameter because the default label would otherwise be "Isbn").,另外此模型使用 `TextField` 來存 `summary` ,因為此文本可能會很長。 + +```python +from django.urls import reverse #Used to generate URLs by reversing the URL patterns + +class Book(models.Model): + """Model representing a book (but not a specific copy of a book).""" + title = models.CharField(max_length=200) + author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) + + # Foreign Key used because book can only have one author, but authors can have multiple books + # Author as a string rather than object because it hasn't been declared yet in the file. + summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book') + isbn = models.CharField('ISBN', max_length=13, help_text='13 Character ISBN number') + + # ManyToManyField used because genre can contain many books. Books can cover many genres. + # Genre class has already been defined so we can specify the object above. + genre = models.ManyToManyField(Genre, help_text='Select a genre for this book') + + def __str__(self): + """String for representing the Model object.""" + return self.title + + def get_absolute_url(self): + """Returns the url to access a detail record for this book.""" + return reverse('book-detail', args=[str(self.id)]) +``` + +「書籍類別」(`genre`)是一個 `ManyToManyField` ,因此一本書可以有很多書籍類別,而一個書結類別也能夠對應到很多本書。作者(`author`)被宣告為外鍵(`ForeignKey`),因此每本書只會有一名作者,但一名作者可能會有多本書(實際上,一本書可能會有多名作者,不過這個案例不會有,所以在別的例子這種作法可能會有問題) + +在上面兩個宣告關聯性模型的敘述句內,關聯的對象都是用對象的模型類或字串的方式作為首個未具名參數的方式傳入句內做宣告。在關聯對象尚未被定義前,若要參照到該對象,必須使用該對象名稱字串的方式來宣告關聯性!還有一些 `author` 欄位的其它值得一提的參數:`null=True` 表示如果沒有作者的話,允許在資料庫中存入 `Null` 值;`on_delete=models.SET_NULL` 表示如果某筆作者紀錄被刪除的話,與該作者相關連的欄位都會被設成 `Null`。 + +這個模型也定義了 `__str__()` ,使用書本的 `title` 字段來表示一筆 `Book` 的紀錄。而最後一個方法,`get_absolute_url()` ,則會回傳一個可以被用來存取該模型細節紀錄的 URL (要讓其有效運作,我們必須定義一個 URL 的映射,我們將其命名為 `book-detail` ,另外還得定義一個關聯示圖(view)與模板(template) )。 + +### 書本詳情模型 (BookInstance model) + +接下來,複製下方 `BookInstance` 的模型,貼在其他模型下面,這個 `BookInstance` 模型表示一個特定的書籍副本(可會被某人借走),並且包含如「副本是否可用」、「預計歸還日期」、「版本說明」或「版本細節」等資訊,還有一個在圖書館中唯一的 id 。 + +有些字段(fields)和方法(methods)現在你也熟悉了。此模型使用了: + +- `ForeignKey` 用來辨識相關的 `Book` (每本書可以有很多副本,但每個副本只能有一個`Book`) +- `CharField` 用來表示該本書的版本說明(特定版本) + +```python +import uuid # Required for unique book instances + +class BookInstance(models.Model): + """Model representing a specific copy of a book (i.e. that can be borrowed from the library).""" + id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular book across whole library') + book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) + imprint = models.CharField(max_length=200) + due_back = models.DateField(null=True, blank=True) + + LOAN_STATUS = ( + ('m', 'Maintenance'), + ('o', 'On loan'), + ('a', 'Available'), + ('r', 'Reserved'), + ) + + status = models.CharField( + max_length=1, + choices=LOAN_STATUS, + blank=True, + default='m', + help_text='Book availability', + ) + + class Meta: + ordering = ['due_back'] + + def __str__(self): + """String for representing the Model object.""" + return f'{self.id} ({self.book.title})' +``` + +我們額外宣告了一些新的字段(field)類別(types): + +- `UUIDField` 被用來將 `id` 字段再這個模型中設定為 `primary_key` ,這類別的字段會分配一個全域唯一的值給每一個實例(instance),也就是任何一本你能在圖書館找到的書。 +- `DateField` 會被用來設定 `due_back` 的日期(紀錄書本何時會被歸還,可再被使用,或者是否正在保養期),這個字段允許 `blank` 或 `null` 值,而當元數據模型 (`Class Meta`)收到請求(query)時也會使用此字段來做資料排序。 +- `status` 是一個 `CharField` 字段,用來定義一個選項列表。你可以看到,我們定義了一個包含「鍵-值對元組」的元組(tuple) 並使其成為選項的參數,鍵-值對中的值會陳列出來並可以被使用者選擇,當選項被選定後,鍵(key)也會被儲存下來。我們也設定了預設的鍵值為 "m" (maintenance) 用來表示當每本書在初始創造還未放上書架時是不可被使用的。 + +而 `__str__()` 模型用來表示 `BookInstance` 這個物件的「唯一 ID」和「相關之 `Book` 書本名稱(title)」的組合。 + +> **備註:** 關於 Python 的小提醒: +> +> - 從 Python3.6 開始,你可以使用「字串插值語法」(又稱做 f-string): +> `f'{self.id} ({self.book.title})'` +> - 在舊版 Python 這部分的教學中,我們則使用了另一種有效的 [formatted string](https://www.python.org/dev/peps/pep-3101/) 語法 +> (e.g. `'{0} ({1})'.format(self.id,self.book.title)`) + +### 作者模型(Author model) + +複製下方 `Author` 的模型程式碼並貼在 **models.py** 文件的最下方。 + +現在所有的字段(fields)與方法(methods)你應該都熟悉了,此模型定義了作者的「名」、「姓」、「出生年月日」、「死亡日期(非必填)」。該模型也指定,預設情況下,`__str__()` 方法會回傳作者姓名(按照姓、名排序)。而 `get_absolute_url()` 方法會反轉 author-detail 的 URL 映射,來獲得顯示單個作者的 URL。 + +```python +class Author(models.Model): + """Model representing an author.""" + first_name = models.CharField(max_length=100) + last_name = models.CharField(max_length=100) + date_of_birth = models.DateField(null=True, blank=True) + date_of_death = models.DateField('Died', null=True, blank=True) + + class Meta: + ordering = ['last_name', 'first_name'] + + def get_absolute_url(self): + """Returns the url to access a particular author instance.""" + return reverse('author-detail', args=[str(self.id)]) + + def __str__(self): + """String for representing the Model object.""" + return f'{self.last_name}, {self.first_name}' +``` + +## 再次執行資料庫遷移(database migrations) + +你的所有模型都建立好了,現在必須再次執行你的資料庫 migrations 指令來將這些修改內容更信到資料庫中。 + + python3 manage.py makemigrations + python3 manage.py migrate + +## 語言模型(Language model) — 挑戰 + +請想像一下,現在來了一位善心人士捐了一堆用不同語言寫的書(例如:波斯語),而你的挑戰是必須制定一個最好在我們的圖說館網站呈現的方式,並把它做成模組。 + +幾件事情需要思考: + +- 「語言」需要與 `Book` 、`BookInstance` 或其他物件(Object)相關聯嗎? +- 「不同語言」能以什麼形式來表示? + 模型?自由文本字段(free text field)?硬編碼選擇列表(hard-coded selection list)? + +當你決定好了,就開始動手吧!你可以在[Github 的這裡](https://github.com/mdn/django-locallibrary-tutorial/blob/master/catalog/models.py)看到我們是怎麼思考的。 + +## 小結 + +在這篇文章我們學到如何定義模型,並且利用這些資訊來設計與實作適合的模型給 _LocalLibrary 網站。_ + +_再來我們要稍微撇開建立網站,先來看看 Django 的管理站(Django Administration site),這個管理站能讓我們加入一些資料到圖書館中,讓我們再來能夠透過「示圖(views)與模板(templates)」(當然我們現在都還沒建立)來展示。_ + +## 延伸閱讀 + +- [Writing your first Django app, part 2](https://docs.djangoproject.com/en/2.0/intro/tutorial02/) (Django docs) +- [Making queries](https://docs.djangoproject.com/en/2.0/topics/db/queries/) (Django Docs) +- [QuerySet API Reference](https://docs.djangoproject.com/en/2.0/ref/models/querysets/) (Django Docs) + +{{PreviousMenuNext("Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django/Admin_site", "Learn/Server-side/Django")}} + +## In this module + +- [Django introduction](/en-US/docs/Learn/Server-side/Django/Introduction) +- [Setting up a Django development environment](/en-US/docs/Learn/Server-side/Django/development_environment) +- [Django Tutorial: The Local Library website](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django Tutorial Part 2: Creating a skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) +- [Django Tutorial Part 3: Using models](/en-US/docs/Learn/Server-side/Django/Models) +- [Django Tutorial Part 4: Django admin site](/en-US/docs/Learn/Server-side/Django/Admin_site) +- [Django Tutorial Part 5: Creating our home page](/en-US/docs/Learn/Server-side/Django/Home_page) +- [Django Tutorial Part 6: Generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views) +- [Django Tutorial Part 7: Sessions framework](/en-US/docs/Learn/Server-side/Django/Sessions) +- [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/Authentication) +- [Django Tutorial Part 9: Working with forms](/en-US/docs/Learn/Server-side/Django/Forms) +- [Django Tutorial Part 10: Testing a Django web application](/en-US/docs/Learn/Server-side/Django/Testing) +- [Django Tutorial Part 11: Deploying Django to production](/en-US/docs/Learn/Server-side/Django/Deployment) +- [Django web application security](/en-US/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django mini blog](/en-US/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/sessions/index.html b/files/zh-tw/learn/server-side/django/sessions/index.html deleted file mode 100644 index 89f2d0d73d9b7e..00000000000000 --- a/files/zh-tw/learn/server-side/django/sessions/index.html +++ /dev/null @@ -1,185 +0,0 @@ ---- -title: 'Django Tutorial Part 7: Sessions framework' -slug: Learn/Server-side/Django/Sessions -translation_of: Learn/Server-side/Django/Sessions ---- -
    {{LearnSidebar}}
    - -
    {{PreviousMenuNext("Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django/authentication_and_sessions", "Learn/Server-side/Django")}}
    - -

    本教程擴展了我們的LocalLibrary 網站,為主頁添加了一個基於會話的訪問計數器。這是一個相對簡單的例子,但它確實顯示了,如何使用會話框架,為匿名用戶提供持久的行為。

    - - - - - - - - - - - - -
    Prerequisites:Complete all previous tutorial topics, including Django Tutorial Part 6: Generic list and detail views
    Objective:To understand how sessions are used.
    - -

    概覽

    - -

    我們在之前的教程中創建的LocalLibrary 網站允許用戶瀏覽目錄中的書籍和作者。 雖然內容是從數據庫動態生成的,但每個用戶在使用該網站時基本上都可以訪問相同的頁面和信息類型。

    - -

    在一個"真實"的庫中,您可能希望根據用戶以前對網站的使用,首選項等為單個用戶提供定制的體驗。例如,您可以隱藏或存儲用戶下次訪問網站時之前已確認的警告消息,或尊重他們的偏好(例如,他們希望在每個頁面上顯示的搜索結果的數量)。

    - -

    會話框架允許您實現這種行為,從而允許您基於每個站點訪問者存儲和檢索任意數據。

    - -

    What are sessions?

    - -

    Web瀏覽器和服務器之間的所有通信都是通過HTTP協議進行的,該協議是無狀態的。該協議是無狀態的事實意味著客戶端和服務器之間的消息是完全相互獨立的-沒有基於先前消息的“序列”或行為的概念。因此,如果您想擁有一個跟踪與客戶之間正在進行的關係的站點,則需要自己實施。

    - -

    會話是Django(以及大多數Internet)使用的機制,用於跟踪站點與特定瀏覽器之間的“狀態”。會話允許您在每個瀏覽器中存儲任意數據,並且只要瀏覽器連接,該數據就可用於站點。然後,與會話相關聯的單個數據項被一個``鍵''引用,該鍵既用於存儲又用於檢索數據。

    - -

    Django使用包含特殊會話ID的cookie來標識每個瀏覽器及其與站點的關聯會話。默認情況下,實際會話數據默認存儲在站點數據庫中(這比將數據存儲在cookie中更安全,因為cookie在cookie中更容易受到惡意用戶的攻擊)。您可以將Django配置為將會話數據存儲在其他位置(緩存,文件或是“安全” Cookie),但是默認位置是一個很好且相對安全的選擇。

    - -

    Enabling sessions

    - -

    當我們創建框架網站時(在教程2中),將自動啟用會話。

    - -

    在項目文件的INSTALLED_APPSMIDDLEWARE 部分中進行配置(locallibrary/locallibrary/settings.py),如下所示:

    - -
    INSTALLED_APPS = [
    -    ...
    -    'django.contrib.sessions',
    -    ....
    -
    -MIDDLEWARE = [
    -    ...
    -    'django.contrib.sessions.middleware.SessionMiddleware',
    -    ....
    - -

    Using sessions

    - -

    您可以從request 參數(作為視圖的第一個參數傳入的HttpRequest )中訪問視圖中的session 屬性。 此會話屬性表示與當前用戶的特定連接(或更確切地說,與當前瀏覽器的連接,由該站點的瀏覽器cookie中的會話ID標識)。

    - -

    session 屬性是一個類似於字典的對象,您可以在視圖中隨意讀取和寫入多次,並根據需要對其進行修改。 您可以執行所有正常的字典操作,包括清除所有數據,測試是否存在鍵,循環訪問數據等。儘管如此,在大多數情況下,您只會使用標準的``字典''API來獲取和設置值。

    - -

    下面的代碼片段顯示瞭如何獲取,設置和刪除與當前會話(瀏覽器)相關的鍵“ my_car”的某些數據。

    - -
    -

    注意: Django的一大優點是,您無需考慮將會話綁定到視圖中當前請求的機制。 如果我們在視圖中使用以下片段,我們將知道有關my_car 的信息僅與發送當前請求的瀏覽器相關聯。

    -
    - -
    # Get a session value by its key (e.g. 'my_car'), raising a KeyError if the key is not present
    -my_car = request.session['my_car']
    -
    -# Get a session value, setting a default if it is not present ('mini')
    -my_car = request.session.get('my_car', 'mini')
    -
    -# Set a session value
    -request.session['my_car'] = 'mini'
    -
    -# Delete a session value
    -del request.session['my_car']
    -
    - -

    該API還提供了許多其他方法,這些方法主要用於管理關聯的會話cookie。 例如,有一些方法可以測試客戶端瀏覽器是否支持cookie,設置和檢查cookie到期日期以及從數據存儲中清除過期的會話。 您可以在如 How to use sessions 找到完整的API(Django文檔)。

    - -

    Saving session data

    - -

    默認情況下,當會話已被修改(分配)或刪除時,Django僅保存到會話數據庫並將會話cookie發送給客戶端。 如果您要使用上一節中所示的會話密鑰更新某些數據,則無需擔心! 例如:

    - -
    # This is detected as an update to the session, so session data is saved.
    -request.session['my_car'] = 'mini'
    - -

    如果您要更新會話數據中的某些信息,則Django將不會識別您已對會話進行了更改並保存了數據(例如,如果要在“ my_car”數據中更改“ wheels”數據, 如下所示)。 在這種情況下,您需要將會話明確標記為已修改。

    - -
    # Session object not directly modified, only data within the session. Session changes not saved!
    -request.session['my_car']['wheels'] = 'alloy'
    -
    -# Set session as modified to force data updates/cookie to be saved.
    -request.session.modified = True
    -
    - -
    -

    注意:您可以更改行為,以便站點可以通過在您的項目設置(locallibrary/locallibrary/settings.py)中添加SESSION_SAVE_EVERY_REQUEST = True 來更新每個請求的數據庫/發送cookie。

    -
    - -

    Simple example — getting visit counts

    - -

    作為一個簡單的真實示例,我們將更新我們的庫以告知當前用戶他們訪問LocalLibrary主頁的次數。

    - -

    打開/ /locallibrary/catalog/views.py,然後進行以下粗體顯示的更改。

    - -
    def index(request):
    -    ...
    -
    -    num_authors = Author.objects.count()  # The 'all()' is implied by default.
    -
    -    # Number of visits to this view, as counted in the session variable.
    -    num_visits = request.session.get('num_visits', 0)
    -    request.session['num_visits'] = num_visits + 1
    -
    -    context = {
    -        'num_books': num_books,
    -        'num_instances': num_instances,
    -        'num_instances_available': num_instances_available,
    -        'num_authors': num_authors,
    -        'num_visits': num_visits,
    -    }
    -
    -    # Render the HTML template index.html with the data in the context variable.
    -    return render(request, 'index.html', context=context)
    - -

    在這裡,我們首先獲取'num_visits'會話密鑰的值,如果之前未設置,則將其設置為0。 每次接收到請求時,我們都將增加該值並將其存儲回會話中(對於下一次用戶訪問該頁面)。 然後將num_visits 變量傳遞到我們的上下文變量中的模板。

    - -
    -

    注意:我們也可能會在此處測試瀏覽器是否甚至支持cookie(例如,請參閱How to use sessions)或設計我們的UI,以便無論是否支持cookie都無關緊要。

    -
    - -

    將以下區塊底部看到的行添加到``動態內容''部分底部的主HTML模板(/locallibrary/catalog/templates/index.html)中以顯示上下文變量:

    - -
    <h2>Dynamic content</h2>
    -
    -<p>The library has the following record counts:</p>
    -<ul>
    -  <li><strong>Books:</strong> \{{ num_books }}</li>
    -  <li><strong>Copies:</strong> \{{ num_instances }}</li>
    -  <li><strong>Copies available:</strong> \{{ num_instances_available }}</li>
    -  <li><strong>Authors:</strong> \{{ num_authors }}</li>
    -</ul>
    -
    -<p>You have visited this page \{{ num_visits }}{% if num_visits == 1 %} time{% else %} times{% endif %}.</p>
    -
    - -

    保存更改,然後重新啟動測試服務器。 每次刷新頁面時,數字都會更新。

    - -

    總結

    - -

    現在,您知道使用會話來改善與匿名用戶的交互是多麼容易。

    - -

    在接下來的文章中,我們將說明身份驗證和授權(權限)框架,並向您展示如何支持用戶帳戶。

    - -

    See also

    - - - -

    {{PreviousMenuNext("Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django/Authentication", "Learn/Server-side/Django")}}

    - -

    In this module

    - - diff --git a/files/zh-tw/learn/server-side/django/sessions/index.md b/files/zh-tw/learn/server-side/django/sessions/index.md new file mode 100644 index 00000000000000..15b4ff070f2967 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/sessions/index.md @@ -0,0 +1,187 @@ +--- +title: 'Django Tutorial Part 7: Sessions framework' +slug: Learn/Server-side/Django/Sessions +translation_of: Learn/Server-side/Django/Sessions +--- +{{LearnSidebar}}{{PreviousMenuNext("Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django/authentication_and_sessions", "Learn/Server-side/Django")}} + +本教程擴展了我們的[LocalLibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) 網站,為主頁添加了一個基於會話的訪問計數器。這是一個相對簡單的例子,但它確實顯示了,如何使用會話框架,為匿名用戶提供持久的行為。 + + + + + + + + + + + + +
    Prerequisites: + Complete all previous tutorial topics, including + Django Tutorial Part 6: Generic list and detail views +
    Objective:To understand how sessions are used.
    + +## 概覽 + +我們在之前的教程中創建的[LocalLibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) 網站允許用戶瀏覽目錄中的書籍和作者。 雖然內容是從數據庫動態生成的,但每個用戶在使用該網站時基本上都可以訪問相同的頁面和信息類型。 + +在一個"真實"的庫中,您可能希望根據用戶以前對網站的使用,首選項等為單個用戶提供定制的體驗。例如,您可以隱藏或存儲用戶下次訪問網站時之前已確認的警告消息,或尊重他們的偏好(例如,他們希望在每個頁面上顯示的搜索結果的數量)。 + +會話框架允許您實現這種行為,從而允許您基於每個站點訪問者存儲和檢索任意數據。 + +## What are sessions? + +Web 瀏覽器和服務器之間的所有通信都是通過 HTTP 協議進行的,該協議是無狀態的。該協議是無狀態的事實意味著客戶端和服務器之間的消息是完全相互獨立的-沒有基於先前消息的“序列”或行為的概念。因此,如果您想擁有一個跟踪與客戶之間正在進行的關係的站點,則需要自己實施。 + +會話是 Django(以及大多數 Internet)使用的機制,用於跟踪站點與特定瀏覽器之間的“狀態”。會話允許您在每個瀏覽器中存儲任意數據,並且只要瀏覽器連接,該數據就可用於站點。然後,與會話相關聯的單個數據項被一個\`\`鍵''引用,該鍵既用於存儲又用於檢索數據。 + +Django 使用包含特殊會話 ID 的 cookie 來標識每個瀏覽器及其與站點的關聯會話。默認情況下,實際會話數據默認存儲在站點數據庫中(這比將數據存儲在 cookie 中更安全,因為 cookie 在 cookie 中更容易受到惡意用戶的攻擊)。您可以將 Django 配置為將會話數據存儲在其他位置(緩存,文件或是“安全” Cookie),但是默認位置是一個很好且相對安全的選擇。 + +## Enabling sessions + +當我們[創建框架網站](/zh-TW/docs/Learn/Server-side/Django/skeleton_website)時(在教程 2 中),將自動啟用會話。 + +在項目文件的`INSTALLED_APPS` 和`MIDDLEWARE` 部分中進行配置(**locallibrary/locallibrary/settings.py**),如下所示: + +```python +INSTALLED_APPS = [ + ... + 'django.contrib.sessions', + .... + +MIDDLEWARE = [ + ... + 'django.contrib.sessions.middleware.SessionMiddleware', + .... +``` + +## Using sessions + +您可以從`request` 參數(作為視圖的第一個參數傳入的`HttpRequest` )中訪問視圖中的`session` 屬性。 此會話屬性表示與當前用戶的特定連接(或更確切地說,與當前瀏覽器的連接,由該站點的瀏覽器 cookie 中的會話 ID 標識)。 + +`session` 屬性是一個類似於字典的對象,您可以在視圖中隨意讀取和寫入多次,並根據需要對其進行修改。 您可以執行所有正常的字典操作,包括清除所有數據,測試是否存在鍵,循環訪問數據等。儘管如此,在大多數情況下,您只會使用標準的\`\`字典''API 來獲取和設置值。 + +下面的代碼片段顯示瞭如何獲取,設置和刪除與當前會話(瀏覽器)相關的鍵“ `my_car`”的某些數據。 + +> **備註:** Django 的一大優點是,您無需考慮將會話綁定到視圖中當前請求的機制。 如果我們在視圖中使用以下片段,我們將知道有關`my_car` 的信息僅與發送當前請求的瀏覽器相關聯。 + +```python +# Get a session value by its key (e.g. 'my_car'), raising a KeyError if the key is not present +my_car = request.session['my_car'] + +# Get a session value, setting a default if it is not present ('mini') +my_car = request.session.get('my_car', 'mini') + +# Set a session value +request.session['my_car'] = 'mini' + +# Delete a session value +del request.session['my_car'] +``` + +該 API 還提供了許多其他方法,這些方法主要用於管理關聯的會話 cookie。 例如,有一些方法可以測試客戶端瀏覽器是否支持 cookie,設置和檢查 cookie 到期日期以及從數據存儲中清除過期的會話。 您可以在如 [How to use sessions](https://docs.djangoproject.com/en/2.0/topics/http/sessions/) 找到完整的 API(Django 文檔)。 + +## Saving session data + +默認情況下,當會話已被修改(分配)或刪除時,Django 僅保存到會話數據庫並將會話 cookie 發送給客戶端。 如果您要使用上一節中所示的會話密鑰更新某些數據,則無需擔心! 例如: + +```python +# This is detected as an update to the session, so session data is saved. +request.session['my_car'] = 'mini' +``` + +如果您要更新會話數據中的某些信息,則 Django 將不會識別您已對會話進行了更改並保存了數據(例如,如果要在“ `my_car`”數據中更改“ `wheels`”數據, 如下所示)。 在這種情況下,您需要將會話明確標記為已修改。 + +```python +# Session object not directly modified, only data within the session. Session changes not saved! +request.session['my_car']['wheels'] = 'alloy' + +# Set session as modified to force data updates/cookie to be saved. +request.session.modified = True +``` + +> **備註:** 您可以更改行為,以便站點可以通過在您的項目設置(**locallibrary/locallibrary/settings.py**)中添加`SESSION_SAVE_EVERY_REQUEST = True` 來更新每個請求的數據庫/發送 cookie。 + +## Simple example — getting visit counts + +作為一個簡單的真實示例,我們將更新我們的庫以告知當前用戶他們訪問 LocalLibrary 主頁的次數。 + +打開/ **/locallibrary/catalog/views.py**,然後進行以下粗體顯示的更改。 + +```python +def index(request): + ... + + num_authors = Author.objects.count() # The 'all()' is implied by default. + + # Number of visits to this view, as counted in the session variable. + num_visits = request.session.get('num_visits', 0) + request.session['num_visits'] = num_visits + 1 + + context = { + 'num_books': num_books, + 'num_instances': num_instances, + 'num_instances_available': num_instances_available, + 'num_authors': num_authors, + 'num_visits': num_visits, + } + + # Render the HTML template index.html with the data in the context variable. + return render(request, 'index.html', context=context) +``` + +在這裡,我們首先獲取`'num_visits'`會話密鑰的值,如果之前未設置,則將其設置為 0。 每次接收到請求時,我們都將增加該值並將其存儲回會話中(對於下一次用戶訪問該頁面)。 然後將`num_visits` 變量傳遞到我們的上下文變量中的模板。 + +> **備註:** 我們也可能會在此處測試瀏覽器是否甚至支持 cookie(例如,請參閱[How to use sessions](https://docs.djangoproject.com/en/2.0/topics/http/sessions/))或設計我們的 UI,以便無論是否支持 cookie 都無關緊要。 + +將以下區塊底部看到的行添加到\`\`動態內容''部分底部的主 HTML 模板(**/locallibrary/catalog/templates/index.html**)中以顯示上下文變量: + +```html +

    Dynamic content

    + +

    The library has the following record counts:

    +
      +
    • Books: \{{ num_books }}
    • +
    • Copies: \{{ num_instances }}
    • +
    • Copies available: \{{ num_instances_available }}
    • +
    • Authors: \{{ num_authors }}
    • +
    + +

    You have visited this page \{{ num_visits }}{% if num_visits == 1 %} time{% else %} times{% endif %}.

    +``` + +保存更改,然後重新啟動測試服務器。 每次刷新頁面時,數字都會更新。 + +## 總結 + +現在,您知道使用會話來改善與匿名用戶的交互是多麼容易。 + +在接下來的文章中,我們將說明身份驗證和授權(權限)框架,並向您展示如何支持用戶帳戶。 + +## See also + +- [How to use sessions](https://docs.djangoproject.com/en/2.0/topics/http/sessions/) (Django docs) + +{{PreviousMenuNext("Learn/Server-side/Django/Generic_views", "Learn/Server-side/Django/Authentication", "Learn/Server-side/Django")}} + +## In this module + +- [Django introduction](/en-US/docs/Learn/Server-side/Django/Introduction) +- [Setting up a Django development environment](/en-US/docs/Learn/Server-side/Django/development_environment) +- [Django Tutorial: The Local Library website](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django Tutorial Part 2: Creating a skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) +- [Django Tutorial Part 3: Using models](/en-US/docs/Learn/Server-side/Django/Models) +- [Django Tutorial Part 4: Django admin site](/en-US/docs/Learn/Server-side/Django/Admin_site) +- [Django Tutorial Part 5: Creating our home page](/en-US/docs/Learn/Server-side/Django/Home_page) +- [Django Tutorial Part 6: Generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views) +- [Django Tutorial Part 7: Sessions framework](/en-US/docs/Learn/Server-side/Django/Sessions) +- [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/Authentication) +- [Django Tutorial Part 9: Working with forms](/en-US/docs/Learn/Server-side/Django/Forms) +- [Django Tutorial Part 10: Testing a Django web application](/en-US/docs/Learn/Server-side/Django/Testing) +- [Django Tutorial Part 11: Deploying Django to production](/en-US/docs/Learn/Server-side/Django/Deployment) +- [Django web application security](/en-US/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django mini blog](/en-US/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/skeleton_website/index.html b/files/zh-tw/learn/server-side/django/skeleton_website/index.html deleted file mode 100644 index 1d3cf3875735c6..00000000000000 --- a/files/zh-tw/learn/server-side/django/skeleton_website/index.html +++ /dev/null @@ -1,388 +0,0 @@ ---- -title: 'Django 教學 2: 創建一個骨架網站' -slug: Learn/Server-side/Django/skeleton_website -translation_of: Learn/Server-side/Django/skeleton_website ---- -
    {{LearnSidebar}}
    - -
    {{PreviousMenuNext("Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django/Models", "Learn/Server-side/Django")}}
    - -

    Django 教學的第二篇文章,會展示怎樣創建一個網站的"框架",在這個框架的基礎上,你可以繼續填充整站使用的 settings, urls,模型(models),視圖(views)和模板(templates )。

    - - - - - - - - - - - - -
    前提:創建 Django 的開發環境。複習 Django 教學。
    目標:能夠使用 Django 提供的工具,搭建你自己的網站。
    - -

    概覽

    - -

    這篇文章會展示怎樣創建一個網站的"框架",在這個框架的基礎上,你可以繼續填充整站使用的settings, urls,模型(models),視圖(views)和模板(templates)(我們會在接下來的文章裡討論)。

    - -

    搭建 “框架” 的過程很直接:

    - -
      -
    1. 使用 django-admin工具創建工程的文件夾,基本的文件模板和工程管理腳本(manage.py)。
    2. -
    3. manage.py 創建一個或多個應用。 -
      -

      注意:一個網站可能由多個部分組成,比如,主要頁面,博客,wiki,下載區域等。Django鼓勵將這些部分作為分開的應用開發。如果這樣的話,在需要可以在不同的工程中復用這些應用。

      -
      -
    4. -
    5. 工程裡註冊新的應用。
    6. -
    7. 為每個應用分配url。
    8. -
    - -

    locallibrary 這個項目創建的網站文件夾和它的工程文件夾都命名為locallibrary。我們只創建一個名為catalog的應用。最高層的項目文件結構如下所示:

    - -
    locallibrary/         # Website folder
    -    manage.py         # Script to run Django tools for this project (created using django-admin)
    -    locallibrary/     # Website/project folder (created using django-admin)
    -    catalog/          # Application folder (created using manage.py)
    -
    - -

    接下來的部分,會詳細討論創建網站框架的過程,並會展示怎麼測試這些變化。最後,我們會討論在這個階段裡,你可以設置的全站配置。

    - -

    創建專案項目

    - -

    首先打開命令提示符/終端,確保您在虛擬環境中,導航到您要存放Django應用程序的位置(在文檔文件夾中,輕鬆找到它的位置),並為您的新網站,創建一個文件夾(在這種情況下:locallibrary)。然後使用cd命令進入該文件夾:

    - -
    mkdir locallibrary
    -cd locallibrary
    - -

    django-admin startproject命令創建新項目,並進入該文件夾。

    - -
    django-admin startproject locallibrary
    -cd locallibrary
    - -

    django-admin工具會創建如下所示的文件夾結構

    - -
    locallibrary/
    -    manage.py
    -    locallibrary/
    -        __init__.py
    -        settings.py
    -        urls.py
    -        wsgi.py
    - -

    locallibrary項目的子文件夾是整個網站的進入點:

    - -
      -
    • __init__.py 是一個空文件,指示 Python 將此目錄視為 Python 套件。
    • -
    • settings.py 包含所有的網站設置。這是可以註冊所有創建的應用的地方,也是靜態文件,數據庫配置的地方,等等。
    • -
    • urls.py定義了網站url到view的映射雖然這裡可以包含所有的url,但是更常見的做法是把應用相關的url包含在相關應用中,你可以在接下來的教程裡看到。
    • -
    • wsgi.py 幫助Django應用和網絡服務器間的通訊。你可以把這個當作模板。
    • -
    - -

    manage.py腳本可以創建應用,和資料庫通訊,啟動開發用網絡服務器。

    - -

    創建 catalog 應用

    - -

    接下來,在locallibrary項目裡,使用下面的命令創建catalog應用(和您項目的manage.py在同一個文件夾下)

    - -
    python3 manage.py startapp catalog
    - -
    -

    注意: Linux/Mac OS X應用可以使用上面的命令。在windows平台下應該改為: py -3 manage.py startapp catalog

    - -

    如果你是windows系統,在這個部分用py -3替代python3

    - -

    如果您使用的是Python 3.7.0,則應使用py manage.py startapp catalog

    -
    - -

    這個工具創建了一個新的文件夾,並為該應用創建了不同的文件(下面黑體所示)。絕大多數文件的命名和它們的目的有關(比如視圖函數就是views.py,模型就是models.py,測試是tests.py,網站管理設置是admin.py,註冊應用是apps.py),並且還包含了為項目所用的最小模板。

    - -

    執行命令後的文件夾結構如下所示:

    - -
    locallibrary/
    -    manage.py
    -    locallibrary/
    -    catalog/
    -        admin.py
    -        apps.py
    -        models.py
    -        tests.py
    -        views.py
    -        __init__.py
    -        migrations/
    -
    - -

    除上面所說的文件外,我們還有:

    - -
      -
    • 一個migration文件夾,用來存放 “migrations” ——當你修改你的數據模型時,這個文件會自動升級你的資料庫。
    • -
    • __init__.py —一個空文件,Django/Python會將這個文件作為Python套件包並允許你在項目的其他部分使用它。
    • -
    - -
    -

    注意 :你注意到上面的文件裡有些缺失嘛?儘管有了 views 和 models 的文件,可是 url 映射,網站模板,靜態文件在哪裡呢?我們會在接下來的部分展示如何創建它們(並不是每個網站都需要,不過這個例子需要)。

    -
    - -

    註冊catalog應用

    - -

    既然應用已經創建好了,我們還必須在項目裡註冊它,以便工具在運行時它會包括在裡面(比如在數據庫裡添加模型時)。在項目的settings裡,把應用添加進INSTALLED_APPS ,就完成了註冊。

    - -

    打開項目設置文件 locallibrary/locallibrary/settings.py找到 INSTALLED_APPS 列表裡的定義。如下所示,在列表的最後添加新的一行。

    - -
    INSTALLED_APPS = [
    -    'django.contrib.admin',
    -    'django.contrib.auth',
    -    'django.contrib.contenttypes',
    -    'django.contrib.sessions',
    -    'django.contrib.messages',
    -    'django.contrib.staticfiles',
    -    'catalog.apps.CatalogConfig', 
    -]
    - -

    新的這行,詳細說明了應用配置文件在( CatalogConfig) /locallibrary/catalog/apps.py 裡,當你創建應用時就完成了這個過程。

    - -
    -

    注意 :注意到INSTALLED_APPS已经有许多其他的应用了 (還有 MIDDLEWARE,在settings的下面)。這些應用為 Django administration site 提供了支持和許多功能(包括會話,認證系統等)。

    -
    - -

    配置資料庫

    - -

    現在可以為項目配置資料庫了——為了避免性能上的差異,最好在生產和開發中使用同一種資料庫。你可以在資料庫 裡找到不同的設置方法(Django文檔)。

    - -

    在這個項目裡,我們使用SQLite。因為在展示用的數據庫中,我們不會有很多並發存取的行為。同時,也因為SQLite不需要額外的配置工作。你可以在settings.py裡看到這個數據庫怎樣配置的。(更多信息如下所示)

    - -
    DATABASES = {
    -    'default': {
    -        'ENGINE': 'django.db.backends.sqlite3',
    -        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    -    }
    -}
    -
    - -

    因為我們使用SQLite,不需要其他的設置了。我們繼續吧!

    - -

    其他項目設置

    - -

    settings.py裡還包括其他的一些設置,現在只需要改變時區 —改為和標準tz時區數據表 裡的字符串相同就可以了(數據表裡的TZ列有你想要的時區)。把TIME_ZONE的值改為你的時區,比如

    - -
    TIME_ZONE = 'Asia/Taipei'
    - -

    有兩個設置你現在不會用到,不過你應該留意:

    - -
      -
    • SECRET_KEY. 這個密匙值,是Django網站安全策略的一部分。如果在開發環境中,沒有保護好這個密匙,把代碼投入生產環境時,最好用不同的密匙代替。(可能從環境變量或文件中讀取)。
    • -
    • DEBUG. 這個會在debug日誌裡輸出錯誤信息,而不是輸入H​​TTP的返回碼。在生產環境中,它應設置為false,因為輸出的錯誤信息,會幫助想要攻擊網站的人。
    • -
    - -

    鏈接URL映射器

    - -

    在項目文件夾裡,創建網站時同時生成了URL映射器(urls.py)。儘管你可以用它來管理所有的URL映射,但是更常用的做法是把URL映射留到它們相關的應用中。

    - -

    打開locallibrary/locallibrary/urls.py 注意指導文字解釋了一些使用URL映射器的方法。

    - -
    """locallibrary URL Configuration
    -
    -The `urlpatterns` list routes URLs to views. For more information please see:
    -    https://docs.djangoproject.com/en/2.0/topics/http/urls/
    -Examples:
    -Function views
    -    1. Add an import:  from my_app import views
    -    2. Add a URL to urlpatterns:  path('', views.home, name='home')
    -Class-based views
    -    1. Add an import:  from other_app.views import Home
    -    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
    -Including another URLconf
    -    1. Import the include() function: from django.urls import include, path
    -    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
    -"""
    -from django.contrib import admin
    -from django.urls import path
    -
    -urlpatterns = [
    -    path('admin/', admin.site.urls),
    -]
    -
    - -

    URL映射通過urlpatterns 變量管理,它是一個path()函數的Python列表。每個path()函數,要么將URL式樣(URL pattern)關聯到特定視圖( specific view),當模式匹配時將會顯示,要么關聯到某個URL式樣列表的測試代碼。(第二種情況下,URL式樣是目標模型裡的“基本URL”). urlpatterns 列表初始化定義了單一函數,把所有帶有 'admin/' 模式的 URL,映射到admin.site.urls。這個函數,包含了Administration應用自己的URL映射定義。

    - -
    -

    注意: path()中的路由是一個字符串,用於定義要匹配的URL模式。該字符串可能包括一個命名變量(在尖括號中),例如'catalog/<id>/'。此模式將匹配 /catalog/any_chars/ 等URL,並將any_chars 作為參數名稱為id 的字符串,傳遞給視圖。我們將在後面的主題中,進一步討論路徑方法和路由模式

    -
    - -

    urlpatterns 列表的下面一行,插入下面的代码。這個新項目包括一個 path() ,它使用模式 catalog/ 轉發請求到模塊 catalog.urls(具有相對 URL /catalog/urls.py 的文件)。

    - -
    # Use include() to add paths from the catalog application
    -from django.conf.urls import include
    -from django.urls import path
    -
    -urlpatterns += [
    -    path('catalog/', include('catalog.urls')),
    -]
    -
    - -

    現在我們把我們網站的根URL(例如127.0.0.1:8000),重新導向URL 127.0.0.1:8000/catalog/;這是項目中唯一的應用,所以我們最好這樣做。為了完成這個目標,我們使用一個特別的視圖函數( RedirectView),當path()函數中的 url 式樣被識別以後(在這個例子中是根 url),就會把第一個參數,也就是新的相對 URL ,重定向到(/catalog/)。

    - -

    把下面的代碼加到文件最後:

    - -
    #Add URL maps to redirect the base URL to our application
    -from django.views.generic import RedirectView
    -urlpatterns += [
    -    path('', RedirectView.as_view(url='/catalog/')),
    -]
    - -

    將路徑函數的第一個參數留空,用以表示'/'。如果您將第一個參數寫為'/',Django會在您啟動開發服務器時給出以下警告:

    - -
    System check identified some issues:
    -
    -WARNINGS:
    -?: (urls.W002) Your URL pattern '/' has a route beginning with a '/'.
    -Remove this slash as it is unnecessary.
    -If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'.
    -
    - -

    Django默認不提供CSS,JavaScript和圖像等靜態文件,但在創建站點時,開發Web服務器這樣做是有用的。作為此URL映射器的最終添加,您可以通過附加以下幾行,在開發期間啟用靜態文件的提供。

    - -

    現在將以下最終區塊,添加到文件的底部:

    - -
    # Use static() to add url mapping to serve static files during development (only)
    -from django.conf import settings
    -from django.conf.urls.static import static
    -
    -urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    -
    - -
    -

    注意: 有許多方法可以擴充urlpatterns列表(上面我們只是使用+= 運算符,附加一個新的列表項,來清楚地分隔舊代碼和新代碼)。我們可以改為在原始列表定義中,包含這個新的模式映射:

    - -
    urlpatterns = [
    -    path('admin/', admin.site.urls),
    -    path('catalog/', include('catalog.urls')),
    -    path('', RedirectView.as_view(url='/catalog/', permanent=True)),
    -] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    -
    - -

    此外,我們將導入行(from django.urls import include)包含在使用它的代碼中(因此很容易看到我們添加的內容),但通常將所有導入行包含在一個Python文件的頂部。

    -
    - -

    最後一步,在catalog文件夾中,創建一個名為urls.py的文件,並添加以下文本,以定義(空)導入的urlpatterns。這是我們在構建應用程序時,添加模式的地方。

    - -
    from django.urls import path
    -from . import views
    -
    -
    -urlpatterns = [
    -
    -]
    -
    - -

    測試網站框架

    - -

    現在我們有了一個完整的框架項目。這個網站現在還什麼都不能做,但是我們仍然要運行,以確保我們的更改是有效的。

    - -

    在運行前,我們應該先運行數據庫遷移。這會更新我們的數據庫並且包含所有安裝的應用(同時去除一些警告)。

    - -

    運行資料庫遷移

    - -

    Django使用對象關係映射器(ORM),將Django代碼中的模型定義,映射到底層資料庫使用的數據結構。當我們更改模型定義時,Django會跟踪更改,並創建資料庫遷移腳本(位於 /locallibrary/catalog/migrations/ ),來自動遷移資料庫中的底層數據結構。

    - -

    當我們創建網站時,Django會自動添加一些模型,供網站的管理部分使用(稍後我們會解釋)。運行以下命令,來定義資料庫中這些模型的表(確認你位於包含 manage.py 的目錄中):

    - -
    python3 manage.py makemigrations
    -python3 manage.py migrate
    -
    - -
    -

    重要: 每次模型改變,都需要運行以上命令,來影響需要存放的數據結構(包括添加和刪除整個模型和單個字段)。

    -
    - -

    makemigrations命令,創建(但不實施)項目中安裝的所有應用程序的遷移(你可以指定應用程序名稱,也可以為單個項目運行遷移)。這讓你有機會在應用這些遷移之前,檢查這些遷移代碼—當你是Django專家時,你可以選擇稍微調整它們。

    - -

    這個 migrate命令,真正對你的資料庫實施遷移(Django跟踪哪些已添加到當前資料庫)。

    - -
    -

    注意: 參見 Migrations (Django 文件) ,了解較少使用的遷移命令的其他信息。

    -
    - -

    運行網站

    - -

    在開發期間,你首先要使用開發網頁服務器,然後用你本機的瀏覽器觀看,來測試你的網站。

    - -
    -

    注意: 這個開發網頁服務器並不夠強大,不足以用於生產使用,但是它使你在開發期間,能非常容易獲得你的 Django 網站和運行它,以此來進行快速測試。默認情況下,服務器會開通(http://127.0.0.1:8000/),但你也可以選擇其他端口。有關更多信息,查閱(django-admin and manage.py: runserver)(Django docs).

    -
    - -

    通過如下runserver命令,運行開發網頁服務器。(同樣的要在manage.py的目錄)

    - -
    python3 manage.py runserver
    -
    - Performing system checks...
    -
    - System check identified no issues (0 silenced).
    - September 22, 2016 - 16:11:26
    - Django version 1.10, using settings 'locallibrary.settings'
    - Starting development server at http://127.0.0.1:8000/
    - Quit the server with CTRL-BREAK.
    -
    - -

    一旦服務器運行,你可以用你的瀏覽器導航到http://127.0.0.1:8000/ 查看。你應該會看到一個錯誤頁面,如下。

    - -

    Django Debug page for Django 2.0

    - -

    別擔心,這個錯誤頁面是預期的結果。因為我們沒有在 catalogs.urls模塊中,定義任何頁面或網址(即是當我們使用一個指向根目錄的URL時,會被重新定向的地方)。

    - -
    -

    注意: 上面的頁面,演示了一個很棒的Django功能 - 自動除錯日誌記錄。只要找不到頁面,或者代碼引發任何錯誤,就會顯示錯誤畫面,其中包含有用的信息。在這種情況下,我們可以看到我們提供的URL,與我們的任何URL模式都不匹配(如列出的那樣)。在生產期間(當我們將網站放在網上時),日誌記錄將被關閉,在這種情況下,將提供信息量較少、但用戶友好的頁面。

    -
    - -

    這個時候,我們知道Django正在工作!

    - -
    -

    注意: 在進行重大更改時,你應該重新運行遷移,並重新測試站點。這不需要很長時間!

    -
    - -

    挑戰自我

    - -

    catalog/ 目錄包含應用程序的視圖、模型、和應用的其他部分,你可以打開這些文件並查看樣板。

    - -

    如上所述,管理站點的URL映射,已經添加到項目的 urls.py。在瀏覽器中查看管理區域,看看會發生什麼(你可以從上面映射,推斷正確的URL)。

    - -
      -
    - -

    總結

    - -

    你現在已經創建了一個完整的骨架網站項目,你可以繼續加入網址、模型、視圖、和模版。

    - -

    現在,Local Library website的骨架已經完成並運行了,是時候開始寫些代碼,讓網站做些它應該做的事了。

    - -

    參見

    - - - -

    {{PreviousMenuNext("Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django/Models", "Learn/Server-side/Django")}}

    - - - -

    本教程連結

    - - diff --git a/files/zh-tw/learn/server-side/django/skeleton_website/index.md b/files/zh-tw/learn/server-side/django/skeleton_website/index.md new file mode 100644 index 00000000000000..e00ec12d43d331 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/skeleton_website/index.md @@ -0,0 +1,371 @@ +--- +title: 'Django 教學 2: 創建一個骨架網站' +slug: Learn/Server-side/Django/skeleton_website +translation_of: Learn/Server-side/Django/skeleton_website +--- +{{LearnSidebar}}{{PreviousMenuNext("Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django/Models", "Learn/Server-side/Django")}} + +Django 教學的第二篇文章,會展示怎樣創建一個網站的"框架",在這個框架的基礎上,你可以繼續填充整站使用的 settings, urls,模型(models),視圖(views)和模板(templates )。 + + + + + + + + + + + + +
    前提:創建 Django 的開發環境。複習 Django 教學。
    目標:能夠使用 Django 提供的工具,搭建你自己的網站。
    + +## 概覽 + +這篇文章會展示怎樣創建一個網站的"框架",在這個框架的基礎上,你可以繼續填充整站使用的 settings, urls,模型(models),視圖(views)和模板(templates)(我們會在接下來的文章裡討論)。 + +搭建 “框架” 的過程很直接: + +1. 使用 `django-admin`工具創建工程的文件夾,基本的文件模板和工程管理腳本(**manage.py**)。 +2. 用 **manage.py** 創建一個或多個*應用*。 + + > **備註:** 一個網站可能由多個部分組成,比如,主要頁面,博客,wiki,下載區域等。Django 鼓勵將這些部分作為分開的應用開發。如果這樣的話,在需要可以在不同的工程中復用這些應用。 + +3. 工程裡註冊新的應用。 +4. 為每個應用分配 url。 + +為 [locallibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) 這個項目創建的網站文件夾和它的工程文件夾都命名為*locallibrary*。我們只創建一個名為*catalog*的應用。最高層的項目文件結構如下所示: + +```bash +locallibrary/ # Website folder + manage.py # Script to run Django tools for this project (created using django-admin) + locallibrary/ # Website/project folder (created using django-admin) + catalog/ # Application folder (created using manage.py) +``` + +接下來的部分,會詳細討論創建網站框架的過程,並會展示怎麼測試這些變化。最後,我們會討論在這個階段裡,你可以設置的全站配置。 + +## 創建專案項目 + +首先打開命令提示符/終端,確保您在[虛擬環境](/zh-TW/docs/Learn/Server-side/Django/development_environment#Using_a_virtual_environment)中,導航到您要存放 Django 應用程序的位置(在文檔文件夾中,輕鬆找到它的位置),並為您的新網站,創建一個文件夾(在這種情況下:locallibrary)。然後使用 cd 命令進入該文件夾: + +```bash +mkdir locallibrary +cd locallibrary +``` + +用`django-admin startproject`命令創建新項目,並進入該文件夾。 + +```bash +django-admin startproject locallibrary +cd locallibrary +``` + +`django-admin`工具會創建如下所示的文件夾結構 + +```bash +locallibrary/ + manage.py + locallibrary/ + __init__.py + settings.py + urls.py + wsgi.py +``` + +locallibrary 項目的子文件夾是整個網站的進入點: + +- **\_\_init\_\_.py** 是一個空文件,指示 Python 將此目錄視為 Python 套件。 +- **settings.py** 包含所有的網站設置。這是可以註冊所有創建的應用的地方,也是靜態文件,數據庫配置的地方,等等。 +- **urls.py**定義了網站 url 到 view 的映射**。**雖然這裡可以包含所有的 url,但是更常見的做法是把應用相關的 url 包含在相關應用中,你可以在接下來的教程裡看到。 +- **wsgi.py** 幫助 Django 應用和網絡服務器間的通訊。你可以把這個當作模板。 + +**manage.py**腳本可以創建應用,和資料庫通訊,啟動開發用網絡服務器。 + +## 創建 catalog 應用 + +接下來,在 locallibrary 項目裡,使用下面的命令創建 catalog 應用(和您項目的**manage.py**在同一個文件夾下) + +```bash +python3 manage.py startapp catalog +``` + +> **備註:** Linux/Mac OS X 應用可以使用上面的命令。在 windows 平台下應該改為: `py -3 manage.py startapp catalog` +> +> 如果你是 windows 系統,在這個部分用`py -3`替代`python3`。 +> +> 如果您使用的是 Python 3.7.0,則應使用`py manage.py startapp catalog` + +這個工具創建了一個新的文件夾,並為該應用創建了不同的文件(下面黑體所示)。絕大多數文件的命名和它們的目的有關(比如視圖函數就是**views.py,**模型就是**models.py,**測試是**tests.py,**網站管理設置是**admin.py,**註冊應用是**apps.py)**,並且還包含了為項目所用的最小模板。 + +執行命令後的文件夾結構如下所示: + +```bash +locallibrary/ + manage.py + locallibrary/ + catalog/ + admin.py + apps.py + models.py + tests.py + views.py + __init__.py + migrations/ +``` + +除上面所說的文件外,我們還有: + +- 一個*migration*文件夾,用來存放 “migrations” ——當你修改你的數據模型時,這個文件會自動升級你的資料庫。 +- **\_\_init\_\_.py** —一個空文件,Django/Python 會將這個文件作為[Python 套件包](https://docs.python.org/3/tutorial/modules.html#packages)並允許你在項目的其他部分使用它。 + +> **備註:** 你注意到上面的文件裡有些缺失嘛?儘管有了 views 和 models 的文件,可是 url 映射,網站模板,靜態文件在哪裡呢?我們會在接下來的部分展示如何創建它們(並不是每個網站都需要,不過這個例子需要)。 + +## 註冊 catalog 應用 + +既然應用已經創建好了,我們還必須在項目裡註冊它,以便工具在運行時它會包括在裡面(比如在數據庫裡添加模型時)。在項目的 settings 裡,把應用添加進`INSTALLED_APPS` ,就完成了註冊。 + +打開項目設置文件 **locallibrary/locallibrary/settings.py**找到 `INSTALLED_APPS` 列表裡的定義。如下所示,在列表的最後添加新的一行。 + +```bash +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'catalog.apps.CatalogConfig', +] +``` + +新的這行,詳細說明了應用配置文件在( `CatalogConfig`) **/locallibrary/catalog/apps.py** 裡,當你創建應用時就完成了這個過程。 + +> **備註:** 注意到`INSTALLED_APPS已经有许多其他的应用了` (還有 `MIDDLEWARE`,在 settings 的下面)。這些應用為 [Django administration site](/en-US/docs/Learn/Server-side/Django/Admin_site) 提供了支持和許多功能(包括會話,認證系統等)。 + +## 配置資料庫 + +現在可以為項目配置資料庫了——為了避免性能上的差異,最好在生產和開發中使用同一種資料庫。你可以在[資料庫](https://docs.djangoproject.com/en/1.10/ref/settings/#databases) 裡找到不同的設置方法(Django 文檔)。 + +在這個項目裡,我們使用 SQLite。因為在展示用的數據庫中,我們不會有很多並發存取的行為。同時,也因為 SQLite 不需要額外的配置工作。你可以在**settings.py**裡看到這個數據庫怎樣配置的。(更多信息如下所示) + +```python +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + } +} +``` + +因為我們使用 SQLite,不需要其他的設置了。我們繼續吧! + +## 其他項目設置 + +settings.py 裡還包括其他的一些設置,現在只需要改變[時區](https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-TIME_ZONE) —改為和標準[tz 時區數據表](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) 裡的字符串相同就可以了(數據表裡的 TZ 列有你想要的時區)。把`TIME_ZONE`的值改為你的時區,比如 + +```python +TIME_ZONE = 'Asia/Taipei' +``` + +有兩個設置你現在不會用到,不過你應該留意: + +- `SECRET_KEY`. 這個密匙值,是 Django 網站安全策略的一部分。如果在開發環境中,沒有保護好這個密匙,把代碼投入生產環境時,最好用不同的密匙代替。(可能從環境變量或文件中讀取)。 +- `DEBUG`. 這個會在 debug 日誌裡輸出錯誤信息,而不是輸入 H​​TTP 的返回碼。在生產環境中,它應設置為 false,因為輸出的錯誤信息,會幫助想要攻擊網站的人。 + +## 鏈接 URL 映射器 + +在項目文件夾裡,創建網站時同時生成了 URL 映射器(**urls.py**)。儘管你可以用它來管理所有的 URL 映射,但是更常用的做法是把 URL 映射留到它們相關的應用中。 + +打開**locallibrary/locallibrary/urls.py** 注意指導文字解釋了一些使用 URL 映射器的方法。 + +```python +"""locallibrary URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/2.0/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path + +urlpatterns = [ + path('admin/', admin.site.urls), +] +``` + +URL 映射通過`urlpatterns` 變量管理,它是一個`path()`函數的 Python 列表。每個`path()`函數,要么將 URL 式樣(URL pattern)關聯到特定視圖( _specific view)_,當模式匹配時將會顯示,要么關聯到某個 URL 式樣列表的測試代碼。(第二種情況下,URL 式樣是目標模型裡的“基本 URL”). `urlpatterns` 列表初始化定義了單一函數,把所有帶有 'admin/' 模式的 URL,映射到`admin.site.urls`。這個函數,包含了 Administration 應用自己的 URL 映射定義。 + +> **備註:** `path()`中的路由是一個字符串,用於定義要匹配的 URL 模式。該字符串可能包括一個命名變量(在尖括號中),例如`'catalog//'`。此模式將匹配 **/catalog/any_chars** 等 URL,並將 any_chars 作為參數名稱為`id` 的字符串,傳遞給視圖。我們將在後面的主題中,進一步討論路徑方法和路由模式 + +在`urlpatterns` 列表的下面一行,插入下面的代码。這個新項目包括一個 `path()` ,它使用模式 `catalog/` 轉發請求到模塊 `catalog.urls`(具有相對 URL **/catalog/urls.py** 的文件)。 + +```python +# Use include() to add paths from the catalog application +from django.conf.urls import include +from django.urls import path + +urlpatterns += [ + path('catalog/', include('catalog.urls')), +] +``` + +現在我們把我們網站的根 URL(例如`127.0.0.1:8000`),重新導向 URL `127.0.0.1:8000/catalog/`;這是項目中唯一的應用,所以我們最好這樣做。為了完成這個目標,我們使用一個特別的視圖函數( `RedirectView`),當`path()`函數中的 url 式樣被識別以後(在這個例子中是根 url),就會把第一個參數,也就是新的相對 URL ,重定向到(`/catalog/`)。 + +把下面的代碼加到文件最後: + +```python +#Add URL maps to redirect the base URL to our application +from django.views.generic import RedirectView +urlpatterns += [ + path('', RedirectView.as_view(url='/catalog/')), +] +``` + +將路徑函數的第一個參數留空,用以表示'/'。如果您將第一個參數寫為'/',Django 會在您啟動開發服務器時給出以下警告: + +```python +System check identified some issues: + +WARNINGS: +?: (urls.W002) Your URL pattern '/' has a route beginning with a '/'. +Remove this slash as it is unnecessary. +If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. +``` + +Django 默認不提供 CSS,JavaScript 和圖像等靜態文件,但在創建站點時,開發 Web 服務器這樣做是有用的。作為此 URL 映射器的最終添加,您可以通過附加以下幾行,在開發期間啟用靜態文件的提供。 + +現在將以下最終區塊,添加到文件的底部: + + # Use static() to add url mapping to serve static files during development (only) + from django.conf import settings + from django.conf.urls.static import static + + urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + +> **備註:** 有許多方法可以擴充`urlpatterns`列表(上面我們只是使用`+= `運算符,附加一個新的列表項,來清楚地分隔舊代碼和新代碼)。我們可以改為在原始列表定義中,包含這個新的模式映射: +> +> ```python +> urlpatterns = [ +> path('admin/', admin.site.urls), +> path('catalog/', include('catalog.urls')), +> path('', RedirectView.as_view(url='/catalog/', permanent=True)), +> ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) +> ``` +> +> 此外,我們將導入行(`from django.urls import include`)包含在使用它的代碼中(因此很容易看到我們添加的內容),但通常將所有導入行包含在一個 Python 文件的頂部。 + +最後一步,在**catalog**文件夾中,創建一個名為**urls.py**的文件,並添加以下文本,以定義(空)導入的`urlpatterns`。這是我們在構建應用程序時,添加模式的地方。 + +```python +from django.urls import path +from . import views + + +urlpatterns = [ + +] +``` + +## 測試網站框架 + +現在我們有了一個完整的框架項目。這個網站現在還什麼都不能做,但是我們仍然要運行,以確保我們的更改是有效的。 + +在運行前,我們應該先運行*數據庫遷移*。這會更新我們的數據庫並且包含所有安裝的應用(同時去除一些警告)。 + +### 運行資料庫遷移 + +Django 使用對象關係映射器(ORM),將 Django 代碼中的模型定義,映射到底層資料庫使用的數據結構。當我們更改模型定義時,Django 會跟踪更改,並創建資料庫遷移腳本(位於 **/locallibrary/catalog/migrations/** ),來自動遷移資料庫中的底層數據結構。 + +當我們創建網站時,Django 會自動添加一些模型,供網站的管理部分使用(稍後我們會解釋)。運行以下命令,來定義資料庫中這些模型的表(確認你位於包含 **manage.py** 的目錄中): + +```bash +python3 manage.py makemigrations +python3 manage.py migrate +``` + +> **警告:** 每次模型改變,都需要運行以上命令,來影響需要存放的數據結構(包括添加和刪除整個模型和單個字段)。 + +該**`makemigrations`**命令,創建(但不實施)項目中安裝的所有應用程序的遷移(你可以指定應用程序名稱,也可以為單個項目運行遷移)。這讓你有機會在應用這些遷移之前,檢查這些遷移代碼—當你是 Django 專家時,你可以選擇稍微調整它們。 + +這個 **`migrate`**命令,真正對你的資料庫實施遷移(Django 跟踪哪些已添加到當前資料庫)。 + +> **備註:** 參見 [Migrations](https://docs.djangoproject.com/en/2.0/topics/migrations/) (Django 文件) ,了解較少使用的遷移命令的其他信息。 + +### 運行網站 + +在開發期間,你首先要使用開發網頁服務器,然後用你本機的瀏覽器觀看,來測試你的網站。 + +> **備註:** 這個開發網頁服務器並不夠強大,不足以用於生產使用,但是它使你在開發期間,能非常容易獲得你的 Django 網站和運行它,以此來進行快速測試。默認情況下,服務器會開通(http\://127.0.0.1:8000/),但你也可以選擇其他端口。有關更多信息,查閱([django-admin and manage.py: runserver](https://docs.djangoproject.com/en/1.10/ref/django-admin/#runserver))(Django docs). + +通過如下`runserver`命令,運行開發網頁服務器。(同樣的要在**manage.py**的目錄) + +```bash +python3 manage.py runserver + + Performing system checks... + + System check identified no issues (0 silenced). + September 22, 2016 - 16:11:26 + Django version 1.10, using settings 'locallibrary.settings' + Starting development server at http://127.0.0.1:8000/ + Quit the server with CTRL-BREAK. +``` + +一旦服務器運行,你可以用你的瀏覽器導航到 查看。你應該會看到一個錯誤頁面,如下。 + +![Django Debug page for Django 2.0](django_404_debug_page.png) + +別擔心,這個錯誤頁面是預期的結果。因為我們沒有在 `catalogs.urls`模塊中,定義任何頁面或網址(即是當我們使用一個指向根目錄的 URL 時,會被重新定向的地方)。 + +> **備註:** 上面的頁面,演示了一個很棒的 Django 功能 - 自動除錯日誌記錄。只要找不到頁面,或者代碼引發任何錯誤,就會顯示錯誤畫面,其中包含有用的信息。在這種情況下,我們可以看到我們提供的 URL,與我們的任何 URL 模式都不匹配(如列出的那樣)。在生產期間(當我們將網站放在網上時),日誌記錄將被關閉,在這種情況下,將提供信息量較少、但用戶友好的頁面。 + +這個時候,我們知道 Django 正在工作! + +> **備註:** 在進行重大更改時,你應該重新運行遷移,並重新測試站點。這不需要很長時間! + +## 挑戰自我 + +該 **catalog/** 目錄包含應用程序的視圖、模型、和應用的其他部分,你可以打開這些文件並查看樣板。 + +如上所述,管理站點的 URL 映射,已經添加到項目的 **urls.py**。在瀏覽器中查看管理區域,看看會發生什麼(你可以從上面映射,推斷正確的 URL)。 + +## 總結 + +你現在已經創建了一個完整的骨架網站項目,你可以繼續加入網址、模型、視圖、和模版。 + +現在,[Local Library website](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website)的骨架已經完成並運行了,是時候開始寫些代碼,讓網站做些它應該做的事了。 + +## 參見 + +- [Writing your first Django app - part 1](https://docs.djangoproject.com/en/2.0/intro/tutorial01/) (Django docs) +- [Applications](https://docs.djangoproject.com/en/2.0/ref/applications/#configuring-applications) (Django Docs). Contains information on configuring applications. + +{{PreviousMenuNext("Learn/Server-side/Django/Tutorial_local_library_website", "Learn/Server-side/Django/Models", "Learn/Server-side/Django")}} + +## 本教程連結 + +- [Django 介紹](/en-US/docs/Learn/Server-side/Django/Introduction) +- [設定 Django 開發環境](/en-US/docs/Learn/Server-side/Django/development_environment) +- [Django 教學: 本地圖書館網站](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django 教學 第 2 部分: 建立網站骨架](/en-US/docs/Learn/Server-side/Django/skeleton_website) +- [Django 教學 第 3 部分: 使用模型](/en-US/docs/Learn/Server-side/Django/Models) +- [Django 教學 第 4 部分: Django 的管理員頁面](/en-US/docs/Learn/Server-side/Django/Admin_site) +- [Django 教學 第 5 部分: 創建我們的首頁](/en-US/docs/Learn/Server-side/Django/Home_page) +- [Django 教學 第 6 部分: 通用列表與詳細視圖](/en-US/docs/Learn/Server-side/Django/Generic_views) +- [Django 教學 第 7 部分: 會話 (Sessions) 框架](/en-US/docs/Learn/Server-side/Django/Sessions) +- [Django 教學 第 8 部分: 使用者的身分驗證與權限](/en-US/docs/Learn/Server-side/Django/Authentication) +- [Django 教學 第 9 部分: 使用表單](/en-US/docs/Learn/Server-side/Django/Forms) +- [Django 教學 第 10 部分: 測試 Django 網頁應用](/en-US/docs/Learn/Server-side/Django/Testing) +- [Django 教學 第 11 部分: 部署 Django 到生產環境(production)](/en-US/docs/Learn/Server-side/Django/Deployment) +- [Django 網頁應用安全](/en-US/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django 迷你部落格](/en-US/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/testing/index.html b/files/zh-tw/learn/server-side/django/testing/index.html deleted file mode 100644 index f9c99861d604cf..00000000000000 --- a/files/zh-tw/learn/server-side/django/testing/index.html +++ /dev/null @@ -1,907 +0,0 @@ ---- -title: 'Django Tutorial Part 10: Testing a Django web application' -slug: Learn/Server-side/Django/Testing -translation_of: Learn/Server-side/Django/Testing ---- -
    {{LearnSidebar}}
    - -
    {{PreviousMenuNext("Learn/Server-side/Django/Forms", "Learn/Server-side/Django/Deployment", "Learn/Server-side/Django")}}
    - -

    隨著網站的增長,他們越來越難以手動測試。不僅要進行更多的測試,而且隨著組件之間的互動,變得越來越複雜,一個區域的小改變,可能會影響到其他區域,所以需要做更多的改變,來確保一切正常運行,並且在進行更多更改時,不會引入錯誤。減輕這些問題的一種方法,是編寫自動化測試,每當您進行更改時,都可以輕鬆可靠地運行測試。本教程演示如何使用 Django 的測試框架,自動化您的網站的單元測試。

    - - - - - - - - - - - - -
    Prerequisites:Complete all previous tutorial topics, including Django Tutorial Part 9: Working with forms.
    Objective:To understand how to write unit tests for Django-based websites.
    - -

    Overview

    - -

    The LocalLibrary currently has pages to display lists of all books and authors, detail views for Book and Author items, a page to renew BookInstances, and pages to create, update, and delete Author items (and Book records too, if you completed the challenge in the forms tutorial). Even with this relatively small site, manually navigating to each page and superficially checking that everything works as expected can take several minutes. As we make changes and grow the site, the time required to manually check that everything works "properly" will only grow. If we were to continue as we are, eventually we'd be spending most of our time testing, and very little time improving our code.

    - -

    Automated tests can really help with this problem! The obvious benefits are that they can be run much faster than manual tests, can test to a much lower level of detail, and test exactly the same functionality every time (human testers are nowhere near as reliable!) Because they are fast, automated tests can be executed more regularly, and if a test fails, they point to exactly where code is not performing as expected.

    - -

    In addition, automated tests can act as the first real-world "user" of your code, forcing you to be rigorous about defining and documenting how your website should behave. Often they are basis for your code examples and documentation. For these reasons, some software development processes start with test definition and implementation, after which the code is written to match the required behavior (e.g. test-driven and behaviour-driven development).

    - -

    This tutorial shows how to write automated tests for Django, by adding a number of tests to the LocalLibrary website.

    - -

    Types of testing

    - -

    There are numerous types, levels, and classifications of tests and testing approaches. The most important automated tests are:

    - -
    -
    Unit tests
    -
    Verify functional behavior of individual components, often to class and function level.
    -
    Regression tests
    -
    Tests that reproduce historic bugs. Each test is initially run to verify that the bug has been fixed, and then re-run to ensure that it has not been reintroduced following later changes to the code.
    -
    Integration tests
    -
    Verify how groupings of components work when used together. Integration tests are aware of the required interactions between components, but not necessarily of the internal operations of each component. They may cover simple groupings of components through to the whole website.
    -
    - -
    -

    Note: Other common types of tests include black box, white box, manual, automated, canary, smoke, conformance, acceptance, functional, system, performance, load, and stress tests. Look them up for more information.

    -
    - -

    What does Django provide for testing?

    - -

    Testing a website is a complex task, because it is made of several layers of logic – from HTTP-level request handling, queries models, to form validation and processing, and template rendering.

    - -

    Django provides a test framework with a small hierarchy of classes that build on the Python standard unittest library. Despite the name, this test framework is suitable for both unit and integration tests. The Django framework adds API methods and tools to help test web and Django-specific behaviour. These allow you to simulate requests, insert test data, and inspect your application's output. Django also provides an API (LiveServerTestCase) and tools for using different testing frameworks, for example you can integrate with the popular Selenium framework to simulate a user interacting with a live browser.

    - -

    To write a test you derive from any of the Django (or unittest) test base classes (SimpleTestCase, TransactionTestCase, TestCase, LiveServerTestCase) and then write separate methods to check that specific functionality works as expected (tests use "assert" methods to test that expressions result in True or False values, or that two values are equal, etc.) When you start a test run, the framework executes the chosen test methods in your derived classes. The test methods are run independently, with common setup and/or tear-down behaviour defined in the class, as shown below.

    - -
    class YourTestClass(TestCase):
    -
    -    def setUp(self):
    -        #Setup run before every test method.
    -        pass
    -
    -    def tearDown(self):
    -        #Clean up run after every test method.
    -        pass
    -
    -    def test_something_that_will_pass(self):
    -        self.assertFalse(False)
    -
    -    def test_something_that_will_fail(self):
    -        self.assertTrue(False)
    -
    - -

    The best base class for most tests is django.test.TestCase. This test class creates a clean database before its tests are run, and runs every test function in its own transaction. The class also owns a test Client that you can use to simulate a user interacting with the code at the view level. In the following sections we're going to concentrate on unit tests, created using this TestCase base class.

    - -
    -

    Note: The django.test.TestCase class is very convenient, but may result in some tests being slower than they need to be (not every test will need to set up its own database or simulate the view interaction). Once you're familiar with what you can do with this class, you may want to replace some of your tests with the available simpler test classes.

    -
    - -

    What should you test?

    - -

    You should test all aspects of your own code, but not any libraries or functionality provided as part of Python or Django.

    - -

    So for example, consider the Author model defined below. You don't need to explicitly test that first_name and last_name have been stored properly as CharField in the database because that is something defined by Django (though of course in practice you will inevitably test this functionality during development). Nor do you need to test that the date_of_birth has been validated to be a date field, because that is again something implemented in Django.

    - -

    However you should check the text used for the labels (First name, Last_name, Date of birth, Died), and the size of the field allocated for the text (100 chars), because these are part of your design and something that could be broken/changed in future.

    - -
    class Author(models.Model):
    -    first_name = models.CharField(max_length=100)
    -    last_name = models.CharField(max_length=100)
    -    date_of_birth = models.DateField(null=True, blank=True)
    -    date_of_death = models.DateField('Died', null=True, blank=True)
    -
    -    def get_absolute_url(self):
    -        return reverse('author-detail', args=[str(self.id)])
    -
    -    def __str__(self):
    -        return '%s, %s' % (self.last_name, self.first_name)
    - -

    Similarly, you should check that the custom methods get_absolute_url() and __str__() behave as required because they are your code/business logic. In the case of get_absolute_url() you can trust that the Django reverse() method has been implemented properly, so what you're testing is that the associated view has actually been defined.

    - -
    -

    Note: Astute readers may note that we would also want to constrain the date of birth and death to sensible values, and check that death comes after birth. In Django this constraint would be added to your form classes (although you can define validators for the fields these appear to only be used at the form level, not the model level).

    -
    - -

    With that in mind lets start looking at how to define and run tests.

    - -

    Test structure overview

    - -

    Before we go into the detail of "what to test", let's first briefly look at where and how tests are defined.

    - -

    Django uses the unittest module’s built-in test discovery, which will discover tests under the current working directory in any file named with the pattern test*.py. Provided you name the files appropriately, you can use any structure you like. We recommend that you create a module for your test code, and have separate files for models, views, forms, and any other types of code you need to test. For example:

    - -
    catalog/
    -  /tests/
    -    __init__.py
    -    test_models.py
    -    test_forms.py
    -    test_views.py
    -
    - -

    Create a file structure as shown above in your LocalLibrary project. The __init__.py should be an empty file (this tells Python that the directory is a package). You can create the three test files by copying and renaming the skeleton test file /catalog/tests.py.

    - -
    -

    Note: The skeleton test file /catalog/tests.py was created automatically when we built the Django skeleton website. It is perfectly "legal" to put all your tests inside it, but if you test properly, you'll quickly end up with a very large and unmanageable test file.

    - -

    Delete the skeleton file as we won't need it.

    -
    - -

    Open /catalog/tests/test_models.py. The file should import django.test.TestCase, as shown:

    - -
    from django.test import TestCase
    -
    -# Create your tests here.
    -
    - -

    Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality. In other cases you may wish to have a separate class for testing a specific use case, with individual test functions that test aspects of that use-case (for example, a class to test that a model field is properly validated, with functions to test each of the possible failure cases). Again, the structure is very much up to you, but it is best if you are consistent.

    - -

    Add the test class below to the bottom of the file. The class demonstrates how to construct a test case class by deriving from TestCase.

    - -
    class YourTestClass(TestCase):
    -
    -    @classmethod
    -    def setUpTestData(cls):
    -        print("setUpTestData: Run once to set up non-modified data for all class methods.")
    -        pass
    -
    -    def setUp(self):
    -        print("setUp: Run once for every test method to setup clean data.")
    -        pass
    -
    -    def test_false_is_false(self):
    -        print("Method: test_false_is_false.")
    -        self.assertFalse(False)
    -
    -    def test_false_is_true(self):
    -        print("Method: test_false_is_true.")
    -        self.assertTrue(False)
    -
    -    def test_one_plus_one_equals_two(self):
    -        print("Method: test_one_plus_one_equals_two.")
    -        self.assertEqual(1 + 1, 2)
    - -

    The new class defines two methods that you can use for pre-test configuration (for example, to create any models or other objects you will need for the test):

    - -
      -
    • setUpTestData() is called once at the beginning of the test run for class-level setup. You'd use this to create objects that aren't going to be modified or changed in any of the test methods.
    • -
    • setUp() is called before every test function to set up any objects that may be modified by the test (every test function will get a "fresh" version of these objects).
    • -
    - -
    -

    The test classes also have a tearDown() method which we haven't used. This method isn't particularly useful for database tests, since the TestCase base class takes care of database teardown for you.

    -
    - -

    Below those we have a number of test methods, which use Assert functions to test whether conditions are true, false or equal (AssertTrue, AssertFalse, AssertEqual). If the condition does not evaluate as expected then the test will fail and report the error to your console.

    - -

    The AssertTrue, AssertFalse, AssertEqual are standard assertions provided by unittest. There are other standard assertions in the framework, and also Django-specific assertions to test if a view redirects (assertRedirects), to test if a particular template has been used (assertTemplateUsed), etc.

    - -
    -

    You should not normally include print() functions in your tests as shown above. We do that here only so that you can see the order that the setup functions are called in the console (in the following section).

    -
    - -

    How to run the tests

    - -

    The easiest way to run all the tests is to use the command:

    - -
    python3 manage.py test
    - -

    This will discover all files named with the pattern test*.py under the current directory and run all tests defined using appropriate base classes (here we have a number of test files, but only /catalog/tests/test_models.py currently contains any tests.) By default the tests will individually report only on test failures, followed by a test summary.

    - -
    -

    If you get errors similar to: ValueError: Missing staticfiles manifest entry ... this may be because testing does not run collectstatic by default and your app is using a storage class that requires it (see manifest_strict for more information). There are a number of ways you can overcome this problem - the easiest is to simply run collectstatic before running the tests:

    - -
    python3 manage.py collectstatic
    -
    -
    - -

    Run the tests in the root directory of LocalLibrary. You should see an output like the one below.

    - -
    >python3 manage.py test
    -
    -Creating test database for alias 'default'...
    -setUpTestData: Run once to set up non-modified data for all class methods.
    -setUp: Run once for every test method to setup clean data.
    -Method: test_false_is_false.
    -.setUp: Run once for every test method to setup clean data.
    -Method: test_false_is_true.
    -FsetUp: Run once for every test method to setup clean data.
    -Method: test_one_plus_one_equals_two.
    -.
    -======================================================================
    -FAIL: test_false_is_true (catalog.tests.tests_models.YourTestClass)
    -----------------------------------------------------------------------
    -Traceback (most recent call last):
    -  File "D:\Github\django_tmp\library_w_t_2\locallibrary\catalog\tests\tests_models.py", line 22, in test_false_is_true
    -    self.assertTrue(False)
    -AssertionError: False is not true
    -
    -----------------------------------------------------------------------
    -Ran 3 tests in 0.075s
    -
    -FAILED (failures=1)
    -Destroying test database for alias 'default'...
    - -

    Here we see that we had one test failure, and we can see exactly what function failed and why (this failure is expected, because False is not True!).

    - -
    -

    Tip: The most important thing to learn from the test output above is that it is much more valuable if you use descriptive/informative names for your objects and methods.

    -
    - -

    The text shown in bold above would not normally appear in the test output (this is generated by the print() functions in our tests). This shows how the setUpTestData() method is called once for the class and setUp() is called before each method.

    - -

    The next sections show how you can run specific tests, and how to control how much information the tests display.

    - -

    Showing more test information

    - -

    If you want to get more information about the test run you can change the verbosity. For example, to list the test successes as well as failures (and a whole bunch of information about how the testing database is set up) you can set the verbosity to "2" as shown:

    - -
    python3 manage.py test --verbosity 2
    - -

    The allowed verbosity levels are 0, 1, 2, and 3, with the default being "1".

    - -

    Running specific tests

    - -

    If you want to run a subset of your tests you can do so by specifying the full dot path to the package(s), module, TestCase subclass or method:

    - -
    python3 manage.py test catalog.tests   # Run the specified module
    -python3 manage.py test catalog.tests.test_models  # Run the specified module
    -python3 manage.py test catalog.tests.test_models.YourTestClass # Run the specified class
    -python3 manage.py test catalog.tests.test_models.YourTestClass.test_one_plus_one_equals_two  # Run the specified method
    -
    - -

    LocalLibrary tests

    - -

    Now we know how to run our tests and what sort of things we need to test, let's look at some practical examples.

    - -
    -

    Note: We won't write every possible test, but this should give you and idea of how tests work, and what more you can do.

    -
    - -

    Models

    - -

    As discussed above, we should test anything that is part of our design or that is defined by code that we have written, but not libraries/code that is already tested by Django or the Python development team.

    - -

    For example, consider the Author model below. Here we should test the labels for all the fields, because even though we haven't explicitly specified most of them, we have a design that says what these values should be. If we don't test the values, then we don't know that the field labels have their intended values. Similarly while we trust that Django will create a field of the specified length, it is worthwhile to specify a test for this length to ensure that it was implemented as planned.

    - -
    class Author(models.Model):
    -    first_name = models.CharField(max_length=100)
    -    last_name = models.CharField(max_length=100)
    -    date_of_birth = models.DateField(null=True, blank=True)
    -    date_of_death = models.DateField('Died', null=True, blank=True)
    -
    -    def get_absolute_url(self):
    -        return reverse('author-detail', args=[str(self.id)])
    -
    -    def __str__(self):
    -        return '%s, %s' % (self.last_name, self.first_name)
    - -

    Open our /catalog/tests/test_models.py, and replace any existing code with the following test code for the Author model.

    - -

    Here you'll see that we first import TestCase and derive our test class (AuthorModelTest) from it, using a descriptive name so we can easily identify any failing tests in the test output. We then call setUpTestData() to create an author object that we will use but not modify in any of the tests.

    - -
    from django.test import TestCase
    -
    -# Create your tests here.
    -
    -from catalog.models import Author
    -
    -class AuthorModelTest(TestCase):
    -
    -    @classmethod
    -    def setUpTestData(cls):
    -        #Set up non-modified objects used by all test methods
    -        Author.objects.create(first_name='Big', last_name='Bob')
    -
    -    def test_first_name_label(self):
    -        author=Author.objects.get(id=1)
    -        field_label = author._meta.get_field('first_name').verbose_name
    -        self.assertEquals(field_label,'first name')
    -
    -    def test_date_of_death_label(self):
    -        author=Author.objects.get(id=1)
    -        field_label = author._meta.get_field('date_of_death').verbose_name
    -        self.assertEquals(field_label,'died')
    -
    -    def test_first_name_max_length(self):
    -        author=Author.objects.get(id=1)
    -        max_length = author._meta.get_field('first_name').max_length
    -        self.assertEquals(max_length,100)
    -
    -    def test_object_name_is_last_name_comma_first_name(self):
    -        author=Author.objects.get(id=1)
    -        expected_object_name = '%s, %s' % (author.last_name, author.first_name)
    -        self.assertEquals(expected_object_name,str(author))
    -
    -    def test_get_absolute_url(self):
    -        author=Author.objects.get(id=1)
    -        #This will also fail if the urlconf is not defined.
    -        self.assertEquals(author.get_absolute_url(),'/catalog/author/1')
    - -

    The field tests check that the values of the field labels (verbose_name) and that the size of the character fields are as expected. These methods all have descriptive names, and follow the same pattern:

    - -
    author=Author.objects.get(id=1)   # Get an author object to test
    -field_label = author._meta.get_field('first_name').verbose_name   # Get the metadata for the required field and use it to query the required field data
    -self.assertEquals(field_label,'first name')  # Compare the value to the expected result
    - -

    The interesting things to note are:

    - -
      -
    • We can't get the verbose_name directly using author.first_name.verbose_name, because author.first_name is a string (not a handle to the first_name object that we can use to access its properties). Instead we need to use the author's _meta attribute to get an instance of the field and use that to query for the additional information.
    • -
    • We chose to use assertEquals(field_label,'first name') rather than assertTrue(field_label == 'first name'). The reason for this is that if the test fails the output for the former tells you what the label actually was, which makes debugging the problem just a little easier.
    • -
    - -
    -

    Note: Tests for the last_name and date_of_birth labels, and also the test for the length of the last_name field have been omitted. Add your own versions now, following the naming conventions and approaches shown above.

    -
    - -

    We also need to test our custom methods. These essentially just check that the object name was constructed as we expected using "Last Name", "First Name" format, and that the URL we get for an Author item is as we would expect.

    - -
    def test_object_name_is_last_name_comma_first_name(self):
    -    author=Author.objects.get(id=1)
    -    expected_object_name = '%s, %s' % (author.last_name, author.first_name)
    -    self.assertEquals(expected_object_name,str(author))
    -
    -def test_get_absolute_url(self):
    -    author=Author.objects.get(id=1)
    -    #This will also fail if the urlconf is not defined.
    -    self.assertEquals(author.get_absolute_url(),'/catalog/author/1')
    - -

    Run the tests now. If you created the Author model as we described in the models tutorial it is quite likely that you will get an error for the date_of_death label as shown below. The test is failing because it was written expecting the label definition to follow Django's convention of not capitalising the first letter of the label (Django does this for you).

    - -
    ======================================================================
    -FAIL: test_date_of_death_label (catalog.tests.test_models.AuthorModelTest)
    -----------------------------------------------------------------------
    -Traceback (most recent call last):
    -  File "D:\...\locallibrary\catalog\tests\test_models.py", line 32, in test_date_of_death_label
    -    self.assertEquals(field_label,'died')
    -AssertionError: 'Died' != 'died'
    -- Died
    -? ^
    -+ died
    -? ^
    - -

    This is a very minor bug, but it does highlight how writing tests can more thoroughly check any assumptions you may have made.

    - -
    -

    Note: Change the label for the date_of_death field (/catalog/models.py) to "died" and re-run the tests.

    -
    - -

    The patterns for testing the other models are similar so we won't continue to discuss these further. Feel free to create your own tests for the our other models.

    - -

    Forms

    - -

    The philosophy for testing your forms is the same as for testing your models; you need to test anything that you've coded or your design specifies, but not the behaviour of the underlying framework and other third party libraries.

    - -

    Generally this means that you should test that the forms have the fields that you want, and that these are displayed with appropriate labels and help text. You don't need to verify that Django validates the field type correctly (unless you created your own custom field and validation) — i.e. you don't need to test that an email field only accepts emails. However you would need to test any additional validation that you expect to be performed on the fields and any messages that your code will generate for errors.

    - -

    Consider our form for renewing books. This has just one field for the renewal date, which will have a label and help text that we will need to verify.

    - -
    class RenewBookForm(forms.Form):
    -    """
    -    Form for a librarian to renew books.
    -    """
    -    renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).")
    -
    -    def clean_renewal_date(self):
    -        data = self.cleaned_data['renewal_date']
    -
    -        #Check date is not in past.
    -        if data < datetime.date.today():
    -            raise ValidationError(_('Invalid date - renewal in past'))
    -        #Check date is in range librarian allowed to change (+4 weeks)
    -        if data > datetime.date.today() + datetime.timedelta(weeks=4):
    -            raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))
    -
    -        # Remember to always return the cleaned data.
    -        return data
    - -

    Open our /catalog/tests/test_forms.py file and replace any existing code with the following test code for the RenewBookForm form. We start by importing our form and some Python and Django libraries to help test time-related functionality. We then declare our form test class in the same way as we did for models, using a descriptive name for our TestCase-derived test class.

    - -
    from django.test import TestCase
    -
    -# Create your tests here.
    -
    -import datetime
    -from django.utils import timezone
    -from catalog.forms import RenewBookForm
    -
    -class RenewBookFormTest(TestCase):
    -
    -    def test_renew_form_date_field_label(self):
    -        form = RenewBookForm()
    -        self.assertTrue(form.fields['renewal_date'].label == None or form.fields['renewal_date'].label == 'renewal date')
    -
    -    def test_renew_form_date_field_help_text(self):
    -        form = RenewBookForm()
    -        self.assertEqual(form.fields['renewal_date'].help_text,'Enter a date between now and 4 weeks (default 3).')
    -
    -    def test_renew_form_date_in_past(self):
    -        date = datetime.date.today() - datetime.timedelta(days=1)
    -        form_data = {'renewal_date': date}
    -        form = RenewBookForm(data=form_data)
    -        self.assertFalse(form.is_valid())
    -
    -    def test_renew_form_date_too_far_in_future(self):
    -        date = datetime.date.today() + datetime.timedelta(weeks=4) + datetime.timedelta(days=1)
    -        form_data = {'renewal_date': date}
    -        form = RenewBookForm(data=form_data)
    -        self.assertFalse(form.is_valid())
    -
    -    def test_renew_form_date_today(self):
    -        date = datetime.date.today()
    -        form_data = {'renewal_date': date}
    -        form = RenewBookForm(data=form_data)
    -        self.assertTrue(form.is_valid())
    -
    -    def test_renew_form_date_max(self):
    -        date = timezone.now() + datetime.timedelta(weeks=4)
    -        form_data = {'renewal_date': date}
    -        form = RenewBookForm(data=form_data)
    -        self.assertTrue(form.is_valid())
    -
    - -

    The first two functions test that the field's label and help_text are as expected. We have to access the field using the fields dictionary (e.g. form.fields['renewal_date']). Note here that we also have to test whether the label value is None, because even though Django will render the correct label it returns None if the value is not explicitly set.

    - -

    The rest of the functions test that the form is valid for renewal dates just inside the acceptable range and invalid for values outside the range. Note how we construct test date values around our current date (datetime.date.today()) using datetime.timedelta() (in this case specifying a number of days or weeks). We then just create the form, passing in our data, and test if it is valid.

    - -
    -

    Note: Here we don't actually use the database or test client. Consider modifying these tests to use SimpleTestCase.

    - -

    We also need to validate that the correct errors are raised if the form is invalid, however this is usually done as part of view processing, so we'll take care of that in the next section.

    -
    - -

    That's all for forms; we do have some others, but they are automatically created by our generic class-based editing views, and should be tested there! Run the tests and confirm that our code still passes!

    - -

    Views

    - -

    To validate our view behaviour we use the Django test Client. This class acts like a dummy web browser that we can use to simulate GET and POST requests on a URL and observe the response. We can see almost everything about the response, from low-level HTTP (result headers and status codes) through to the template we're using to render the HTML and the context data we're passing to it. We can also see the chain of redirects (if any) and check the URL and status code at each step. This allows us to verify that each view is doing what is expected.

    - -

    Let's start with one of our simplest views, which provides a list of all Authors. This is displayed at URL /catalog/authors/ (an URL named 'authors' in the URL configuration).

    - -
    class AuthorListView(generic.ListView):
    -    model = Author
    -    paginate_by = 10
    -
    - -

    As this is a generic list view almost everything is done for us by Django. Arguably if you trust Django then the only thing you need to test is that the view is accessible at the correct URL and can be accessed using its name. However if you're using a test-driven development process you'll start by writing tests that confirm that the view displays all Authors, paginating them in lots of 10.

    - -

    Open the /catalog/tests/test_views.py file and replace any existing text with the following test code for AuthorListView. As before we import our model and some useful classes. In the setUpTestData() method we set up a number of Author objects so that we can test our pagination.

    - -
    from django.test import TestCase
    -
    -# Create your tests here.
    -
    -from catalog.models import Author
    -from django.urls import reverse
    -
    -class AuthorListViewTest(TestCase):
    -
    -    @classmethod
    -    def setUpTestData(cls):
    -        #Create 13 authors for pagination tests
    -        number_of_authors = 13
    -        for author_num in range(number_of_authors):
    -            Author.objects.create(first_name='Christian %s' % author_num, last_name = 'Surname %s' % author_num,)
    -
    -    def test_view_url_exists_at_desired_location(self):
    -        resp = self.client.get('/catalog/authors/')
    -        self.assertEqual(resp.status_code, 200)
    -
    -    def test_view_url_accessible_by_name(self):
    -        resp = self.client.get(reverse('authors'))
    -        self.assertEqual(resp.status_code, 200)
    -
    -    def test_view_uses_correct_template(self):
    -        resp = self.client.get(reverse('authors'))
    -        self.assertEqual(resp.status_code, 200)
    -
    -        self.assertTemplateUsed(resp, 'catalog/author_list.html')
    -
    -    def test_pagination_is_ten(self):
    -        resp = self.client.get(reverse('authors'))
    -        self.assertEqual(resp.status_code, 200)
    -        self.assertTrue('is_paginated' in resp.context)
    -        self.assertTrue(resp.context['is_paginated'] == True)
    -        self.assertTrue( len(resp.context['author_list']) == 10)
    -
    -    def test_lists_all_authors(self):
    -        #Get second page and confirm it has (exactly) remaining 3 items
    -        resp = self.client.get(reverse('authors')+'?page=2')
    -        self.assertEqual(resp.status_code, 200)
    -        self.assertTrue('is_paginated' in resp.context)
    -        self.assertTrue(resp.context['is_paginated'] == True)
    -        self.assertTrue( len(resp.context['author_list']) == 3)
    - -

    All the tests use the client (belonging to our TestCase's derived class) to simulate a GET request and get a response (resp). The first version checks a specific URL (note, just the specific path without the domain) while the second generates the URL from its name in the URL configuration.

    - -
    resp = self.client.get('/catalog/authors/')
    -resp = self.client.get(reverse('authors'))
    -
    - -

    Once we have the response we query it for its status code, the template used, whether or not the response is paginated, the number of items returned, and the total number of items.

    - -

    The most interesting variable we demonstrate above is resp.context, which is the context variable passed to the template by the view. This is incredibly useful for testing, because it allows us to confirm that our template is getting all the data it needs. In other words we can check that we're using the intended template and what data the template is getting, which goes a long way to verifying that any rendering issues are solely due to template.

    - -

    Views that are restricted to logged in users

    - -

    In some cases you'll want to test a view that is restricted to just logged in users. For example our LoanedBooksByUserListView is very similar to our previous view but is only available to logged in users, and only displays BookInstance records that are borrowed by the current user, have the 'on loan' status, and are ordered "oldest first".

    - -
    from django.contrib.auth.mixins import LoginRequiredMixin
    -
    -class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView):
    -    """
    -    Generic class-based view listing books on loan to current user.
    -    """
    -    model = BookInstance
    -    template_name ='catalog/bookinstance_list_borrowed_user.html'
    -    paginate_by = 10
    -
    -    def get_queryset(self):
    -        return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')
    - -

    Add the following test code to /catalog/tests/test_views.py. Here we first use SetUp() to create some user login accounts and BookInstance objects (along with their associated books and other records) that we'll use later in the tests. Half of the books are borrowed by each test user, but we've initially set the status of all books to "maintenance". We've used SetUp() rather than setUpTestData() because we'll be modifying some of these objects later.

    - -
    -

    Note: The setUp() code below creates a book with a specified Language, but your code may not include the Language model as this was created as a challenge. If this is the case, simply comment out the parts of the code that create or import Language objects. You should also do this in the RenewBookInstancesViewTest section that follows.

    -
    - -
    import datetime
    -from django.utils import timezone
    -
    -from catalog.models import BookInstance, Book, Genre, Language
    -from django.contrib.auth.models import User #Required to assign User as a borrower
    -
    -class LoanedBookInstancesByUserListViewTest(TestCase):
    -
    -    def setUp(self):
    -        #Create two users
    -        test_user1 = User.objects.create_user(username='testuser1', password='12345')
    -        test_user1.save()
    -        test_user2 = User.objects.create_user(username='testuser2', password='12345')
    -        test_user2.save()
    -
    -        #Create a book
    -        test_author = Author.objects.create(first_name='John', last_name='Smith')
    -        test_genre = Genre.objects.create(name='Fantasy')
    -        test_language = Language.objects.create(name='English')
    -        test_book = Book.objects.create(title='Book Title', summary = 'My book summary', isbn='ABCDEFG', author=test_author, language=test_language)
    -        # Create genre as a post-step
    -        genre_objects_for_book = Genre.objects.all()
    -        test_book.genre.set(genre_objects_for_book) #Direct assignment of many-to-many types not allowed.
    -        test_book.save()
    -
    -        #Create 30 BookInstance objects
    -        number_of_book_copies = 30
    -        for book_copy in range(number_of_book_copies):
    -            return_date= timezone.now() + datetime.timedelta(days=book_copy%5)
    -            if book_copy % 2:
    -                the_borrower=test_user1
    -            else:
    -                the_borrower=test_user2
    -            status='m'
    -            BookInstance.objects.create(book=test_book,imprint='Unlikely Imprint, 2016', due_back=return_date, borrower=the_borrower, status=status)
    -
    -    def test_redirect_if_not_logged_in(self):
    -        resp = self.client.get(reverse('my-borrowed'))
    -        self.assertRedirects(resp, '/accounts/login/?next=/catalog/mybooks/')
    -
    -    def test_logged_in_uses_correct_template(self):
    -        login = self.client.login(username='testuser1', password='12345')
    -        resp = self.client.get(reverse('my-borrowed'))
    -
    -        #Check our user is logged in
    -        self.assertEqual(str(resp.context['user']), 'testuser1')
    -        #Check that we got a response "success"
    -        self.assertEqual(resp.status_code, 200)
    -
    -        #Check we used correct template
    -        self.assertTemplateUsed(resp, 'catalog/bookinstance_list_borrowed_user.html')
    -
    - -

    To verify that the view will redirect to a login page if the user is not logged in we use assertRedirects, as demonstrated in test_redirect_if_not_logged_in(). To verify that the page is displayed for a logged in user we first log in our test user, and then access the page again and check that we get a status_code of 200 (success).

    - -

    The rest of the tests verify that our view only returns books that are on loan to our current borrower. Copy the (self-explanatory) code at the end of the test class above.

    - -
        def test_only_borrowed_books_in_list(self):
    -        login = self.client.login(username='testuser1', password='12345')
    -        resp = self.client.get(reverse('my-borrowed'))
    -
    -        #Check our user is logged in
    -        self.assertEqual(str(resp.context['user']), 'testuser1')
    -        #Check that we got a response "success"
    -        self.assertEqual(resp.status_code, 200)
    -
    -        #Check that initially we don't have any books in list (none on loan)
    -        self.assertTrue('bookinstance_list' in resp.context)
    -        self.assertEqual( len(resp.context['bookinstance_list']),0)
    -
    -        #Now change all books to be on loan
    -        get_ten_books = BookInstance.objects.all()[:10]
    -
    -        for copy in get_ten_books:
    -            copy.status='o'
    -            copy.save()
    -
    -        #Check that now we have borrowed books in the list
    -        resp = self.client.get(reverse('my-borrowed'))
    -        #Check our user is logged in
    -        self.assertEqual(str(resp.context['user']), 'testuser1')
    -        #Check that we got a response "success"
    -        self.assertEqual(resp.status_code, 200)
    -
    -        self.assertTrue('bookinstance_list' in resp.context)
    -
    -        #Confirm all books belong to testuser1 and are on loan
    -        for bookitem in resp.context['bookinstance_list']:
    -            self.assertEqual(resp.context['user'], bookitem.borrower)
    -            self.assertEqual('o', bookitem.status)
    -
    -    def test_pages_ordered_by_due_date(self):
    -
    -        #Change all books to be on loan
    -        for copy in BookInstance.objects.all():
    -            copy.status='o'
    -            copy.save()
    -
    -        login = self.client.login(username='testuser1', password='12345')
    -        resp = self.client.get(reverse('my-borrowed'))
    -
    -        #Check our user is logged in
    -        self.assertEqual(str(resp.context['user']), 'testuser1')
    -        #Check that we got a response "success"
    -        self.assertEqual(resp.status_code, 200)
    -
    -        #Confirm that of the items, only 10 are displayed due to pagination.
    -        self.assertEqual( len(resp.context['bookinstance_list']),10)
    -
    -        last_date=0
    -        for copy in resp.context['bookinstance_list']:
    -            if last_date==0:
    -                last_date=copy.due_back
    -            else:
    -                self.assertTrue(last_date <= copy.due_back)
    - -

    You could also add pagination tests, should you so wish!

    - -

    Testing views with forms

    - -

    Testing views with forms is a little more complicated than in the cases above, because you need to test more code paths: initial display, display after data validation has failed, and display after validation has succeeded. The good news is that we use the client for testing in almost exactly the same way as we did for display-only views.

    - -

    To demonstrate, let's write some tests for the view used to renew books (renew_book_librarian()):

    - -
    from .forms import RenewBookForm
    -
    -@permission_required('catalog.can_mark_returned')
    -def renew_book_librarian(request, pk):
    -    """
    -    View function for renewing a specific BookInstance by librarian
    -    """
    -    book_inst=get_object_or_404(BookInstance, pk = pk)
    -
    -    # If this is a POST request then process the Form data
    -    if request.method == 'POST':
    -
    -        # Create a form instance and populate it with data from the request (binding):
    -        form = RenewBookForm(request.POST)
    -
    -        # Check if the form is valid:
    -        if form.is_valid():
    -            # process the data in form.cleaned_data as required (here we just write it to the model due_back field)
    -            book_inst.due_back = form.cleaned_data['renewal_date']
    -            book_inst.save()
    -
    -            # redirect to a new URL:
    -            return HttpResponseRedirect(reverse('all-borrowed') )
    -
    -    # If this is a GET (or any other method) create the default form
    -    else:
    -        proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
    -        form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,})
    -
    -    return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst})
    - -

    We'll need to test that the view is only available to users who have the can_mark_returned permission, and that users are redirected to an HTTP 404 error page if they attempt to renew a BookInstance that does not exist. We should check that the initial value of the form is seeded with a date three weeks in the future, and that if validation succeeds we're redirected to the "all-borrowed books" view. As part of checking the validation-fail tests we'll also check that our form is sending the appropriate error messages.

    - -

    Add the first part of the test class (shown below) to the bottom of /catalog/tests/test_views.py. This creates two users and two book instances, but only gives one user the permission required to access the view. The code to grant permissions during tests is shown in bold:

    - -
    from django.contrib.auth.models import Permission # Required to grant the permission needed to set a book as returned.
    -
    -class RenewBookInstancesViewTest(TestCase):
    -
    -    def setUp(self):
    -        #Create a user
    -        test_user1 = User.objects.create_user(username='testuser1', password='12345')
    -        test_user1.save()
    -
    -        test_user2 = User.objects.create_user(username='testuser2', password='12345')
    -        test_user2.save()
    -        permission = Permission.objects.get(name='Set book as returned')
    -        test_user2.user_permissions.add(permission)
    -        test_user2.save()
    -
    -        #Create a book
    -        test_author = Author.objects.create(first_name='John', last_name='Smith')
    -        test_genre = Genre.objects.create(name='Fantasy')
    -        test_language = Language.objects.create(name='English')
    -        test_book = Book.objects.create(title='Book Title', summary = 'My book summary', isbn='ABCDEFG', author=test_author, language=test_language,)
    -        # Create genre as a post-step
    -        genre_objects_for_book = Genre.objects.all()
    -        test_book.genre.set(genre_objects_for_book) # Direct assignment of many-to-many types not allowed.
    -        test_book.save()
    -
    -        #Create a BookInstance object for test_user1
    -        return_date= datetime.date.today() + datetime.timedelta(days=5)
    -        self.test_bookinstance1=BookInstance.objects.create(book=test_book,imprint='Unlikely Imprint, 2016', due_back=return_date, borrower=test_user1, status='o')
    -
    -        #Create a BookInstance object for test_user2
    -        return_date= datetime.date.today() + datetime.timedelta(days=5)
    -        self.test_bookinstance2=BookInstance.objects.create(book=test_book,imprint='Unlikely Imprint, 2016', due_back=return_date, borrower=test_user2, status='o')
    - -

    Add the following tests to the bottom of the test class. These check that only users with the correct permissions (testuser2) can access the view. We check all the cases: when the user is not logged in, when a user is logged in but does not have the correct permissions, when the user has permissions but is not the borrower (should succeed), and what happens when they try to access a BookInstance that doesn't exist. We also check that the correct template is used.

    - -
        def test_redirect_if_not_logged_in(self):
    -        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) )
    -        #Manually check redirect (Can't use assertRedirect, because the redirect URL is unpredictable)
    -        self.assertEqual( resp.status_code,302)
    -        self.assertTrue( resp.url.startswith('/accounts/login/') )
    -
    -    def test_redirect_if_logged_in_but_not_correct_permission(self):
    -        login = self.client.login(username='testuser1', password='12345')
    -        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) )
    -
    -        #Manually check redirect (Can't use assertRedirect, because the redirect URL is unpredictable)
    -        self.assertEqual( resp.status_code,302)
    -        self.assertTrue( resp.url.startswith('/accounts/login/') )
    -
    -    def test_logged_in_with_permission_borrowed_book(self):
    -        login = self.client.login(username='testuser2', password='12345')
    -        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance2.pk,}) )
    -
    -        #Check that it lets us login - this is our book and we have the right permissions.
    -        self.assertEqual( resp.status_code,200)
    -
    -    def test_logged_in_with_permission_another_users_borrowed_book(self):
    -        login = self.client.login(username='testuser2', password='12345')
    -        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) )
    -
    -        #Check that it lets us login. We're a librarian, so we can view any users book
    -        self.assertEqual( resp.status_code,200)
    -
    -    def test_HTTP404_for_invalid_book_if_logged_in(self):
    -        import uuid
    -        test_uid = uuid.uuid4() #unlikely UID to match our bookinstance!
    -        login = self.client.login(username='testuser2', password='12345')
    -        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':test_uid,}) )
    -        self.assertEqual( resp.status_code,404)
    -
    -    def test_uses_correct_template(self):
    -        login = self.client.login(username='testuser2', password='12345')
    -        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) )
    -        self.assertEqual( resp.status_code,200)
    -
    -        #Check we used correct template
    -        self.assertTemplateUsed(resp, 'catalog/book_renew_librarian.html')
    -
    - -

    Add the next test method, as shown below. This checks that the initial date for the form is three weeks in the future. Note how we are able to access the value of the initial value of the form field (shown in bold).

    - -
        def test_form_renewal_date_initially_has_date_three_weeks_in_future(self):
    -        login = self.client.login(username='testuser2', password='12345')
    -        resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) )
    -        self.assertEqual( resp.status_code,200)
    -
    -        date_3_weeks_in_future = datetime.date.today() + datetime.timedelta(weeks=3)
    -        self.assertEqual(resp.context['form'].initial['renewal_date'], date_3_weeks_in_future )
    -
    - -

    The next test (add this to the class too) checks that the view redirects to a list of all borrowed books if renewal succeeds. What differs here is that for the first time we show how you can POST data using the client. The post data is the second argument to the post function, and is specified as a dictionary of key/values.

    - -
        def test_redirects_to_all_borrowed_book_list_on_success(self):
    -        login = self.client.login(username='testuser2', password='12345')
    -        valid_date_in_future = datetime.date.today() + datetime.timedelta(weeks=2)
    -        resp = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal_date':valid_date_in_future} )
    -        self.assertRedirects(resp, reverse('all-borrowed') )
    -
    - -
    -

    The all-borrowed view was added as a challenge, and your code may instead redirect to the home page '/'. If so, modify the last two lines of the test code to be like the code below. The follow=True in the request ensures that the request returns the final destination URL (hence checking /catalog/ rather than /).

    - -
     resp = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal_date':valid_date_in_future},follow=True )
    - self.assertRedirects(resp, '/catalog/')
    -
    - -

    Copy the last two functions into the class, as seen below. These again test POST requests, but in this case with invalid renewal dates. We use assertFormError() to verify that the error messages are as expected.

    - -
        def test_form_invalid_renewal_date_past(self):
    -        login = self.client.login(username='testuser2', password='12345')
    -        date_in_past = datetime.date.today() - datetime.timedelta(weeks=1)
    -        resp = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal_date':date_in_past} )
    -        self.assertEqual( resp.status_code,200)
    -        self.assertFormError(resp, 'form', 'renewal_date', 'Invalid date - renewal in past')
    -
    -    def test_form_invalid_renewal_date_future(self):
    -        login = self.client.login(username='testuser2', password='12345')
    -        invalid_date_in_future = datetime.date.today() + datetime.timedelta(weeks=5)
    -        resp = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal_date':invalid_date_in_future} )
    -        self.assertEqual( resp.status_code,200)
    -        self.assertFormError(resp, 'form', 'renewal_date', 'Invalid date - renewal more than 4 weeks ahead')
    -
    - -

    The same sorts of techniques can be used to test the other view.

    - -

    Templates

    - -

    Django provides test APIs to check that the correct template is being called by your views, and to allow you to verify that the correct information is being sent. There is however no specific API support for testing in Django that your HTML output is rendered as expected.

    - - - -

    Django's test framework can help you write effective unit and integration tests — we've only scratched the surface of what the underlying unittest framework can do, let alone Django's additions (for example, check out how you can use unittest.mock to patch third party libraries so you can more thoroughly test your own code).

    - -

    While there are numerous other test tools that you can use, we'll just highlight two:

    - -
      -
    • Coverage: This Python tool reports on how much of your code is actually executed by your tests. It is particularly useful when you're getting started, and you are trying to work out exactly what you should test.
    • -
    • Selenium is a framework to automate testing in a real browser. It allows you to simulate a real user interacting with the site, and provides a great framework for system testing your site (the next step up from integration testing).
    • -
    - -

    Challenge yourself

    - -

    There are a lot more models and views we can test. As a simple task, try to create a test case for the AuthorCreate view.

    - -
    class AuthorCreate(PermissionRequiredMixin, CreateView):
    -    model = Author
    -    fields = '__all__'
    -    initial={'date_of_death':'12/10/2016',}
    -    permission_required = 'catalog.can_mark_returned'
    - -

    Remember that you need to check anything that you specify or that is part of the design. This will include who has access, the initial date, the template used, and where the view redirects on success.

    - -

    Summary

    - -

    Writing test code is neither fun nor glamorous, and is consequently often left to last (or not at all) when creating a website. It is however an essential part of making sure that your code is safe to release after making changes, and cost-effective to maintain.

    - -

    In this tutorial we've shown you how to write and run tests for your models, forms, and views. Most importantly we've provided a brief summary of what you should test, which is often the hardest thing to work out when you're getting started. There is a lot more to know, but even with what you've learned already you should be able to create effective unit tests for your websites.

    - -

    The next and final tutorial shows how you can deploy your wonderful (and fully tested!) Django website.

    - -

    See also

    - - - -

    {{PreviousMenuNext("Learn/Server-side/Django/Forms", "Learn/Server-side/Django/Deployment", "Learn/Server-side/Django")}}

    - -

    - -

    In this module

    - - - -

    diff --git a/files/zh-tw/learn/server-side/django/testing/index.md b/files/zh-tw/learn/server-side/django/testing/index.md new file mode 100644 index 00000000000000..4a7ad40560445f --- /dev/null +++ b/files/zh-tw/learn/server-side/django/testing/index.md @@ -0,0 +1,913 @@ +--- +title: 'Django Tutorial Part 10: Testing a Django web application' +slug: Learn/Server-side/Django/Testing +translation_of: Learn/Server-side/Django/Testing +--- +{{LearnSidebar}}{{PreviousMenuNext("Learn/Server-side/Django/Forms", "Learn/Server-side/Django/Deployment", "Learn/Server-side/Django")}} + +隨著網站的增長,他們越來越難以手動測試。不僅要進行更多的測試,而且隨著組件之間的互動,變得越來越複雜,一個區域的小改變,可能會影響到其他區域,所以需要做更多的改變,來確保一切正常運行,並且在進行更多更改時,不會引入錯誤。減輕這些問題的一種方法,是編寫自動化測試,每當您進行更改時,都可以輕鬆可靠地運行測試。本教程演示如何使用 Django 的測試框架,自動化您的網站的單元測試。 + + + + + + + + + + + + +
    Prerequisites: + Complete all previous tutorial topics, including + Django Tutorial Part 9: Working with forms. +
    Objective:To understand how to write unit tests for Django-based websites.
    + +## Overview + +The [LocalLibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) currently has pages to display lists of all books and authors, detail views for `Book` and `Author` items, a page to renew `BookInstance`s, and pages to create, update, and delete `Author` items (and `Book` records too, if you completed the _challenge_ in the [forms tutorial](/en-US/docs/Learn/Server-side/Django/Forms)). Even with this relatively small site, manually navigating to each page and _superficially_ checking that everything works as expected can take several minutes. As we make changes and grow the site, the time required to manually check that everything works "properly" will only grow. If we were to continue as we are, eventually we'd be spending most of our time testing, and very little time improving our code. + +Automated tests can really help with this problem! The obvious benefits are that they can be run much faster than manual tests, can test to a much lower level of detail, and test exactly the same functionality every time (human testers are nowhere near as reliable!) Because they are fast, automated tests can be executed more regularly, and if a test fails, they point to exactly where code is not performing as expected. + +In addition, automated tests can act as the first real-world "user" of your code, forcing you to be rigorous about defining and documenting how your website should behave. Often they are basis for your code examples and documentation. For these reasons, some software development processes start with test definition and implementation, after which the code is written to match the required behavior (e.g. [test-driven](https://en.wikipedia.org/wiki/Test-driven_development) and [behaviour-driven](https://en.wikipedia.org/wiki/Behavior-driven_development) development). + +This tutorial shows how to write automated tests for Django, by adding a number of tests to the _LocalLibrary_ website. + +### Types of testing + +There are numerous types, levels, and classifications of tests and testing approaches. The most important automated tests are: + +- Unit tests + - : Verify functional behavior of individual components, often to class and function level. +- Regression tests + - : Tests that reproduce historic bugs. Each test is initially run to verify that the bug has been fixed, and then re-run to ensure that it has not been reintroduced following later changes to the code. +- Integration tests + - : Verify how groupings of components work when used together. Integration tests are aware of the required interactions between components, but not necessarily of the internal operations of each component. They may cover simple groupings of components through to the whole website. + +> **備註:** Other common types of tests include black box, white box, manual, automated, canary, smoke, conformance, acceptance, functional, system, performance, load, and stress tests. Look them up for more information. + +### What does Django provide for testing? + +Testing a website is a complex task, because it is made of several layers of logic – from HTTP-level request handling, queries models, to form validation and processing, and template rendering. + +Django provides a test framework with a small hierarchy of classes that build on the Python standard [`unittest`](https://docs.python.org/3/library/unittest.html#module-unittest) library. Despite the name, this test framework is suitable for both unit and integration tests. The Django framework adds API methods and tools to help test web and Django-specific behaviour. These allow you to simulate requests, insert test data, and inspect your application's output. Django also provides an API ([LiveServerTestCase](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#liveservertestcase)) and tools for [using different testing frameworks](https://docs.djangoproject.com/en/2.0/topics/testing/advanced/#other-testing-frameworks), for example you can integrate with the popular [Selenium](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Your_own_automation_environment) framework to simulate a user interacting with a live browser. + +To write a test you derive from any of the Django (or _unittest_) test base classes ([SimpleTestCase](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#simpletestcase), [TransactionTestCase](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#transactiontestcase), [TestCase](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#testcase), [LiveServerTestCase](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#liveservertestcase)) and then write separate methods to check that specific functionality works as expected (tests use "assert" methods to test that expressions result in `True` or `False` values, or that two values are equal, etc.) When you start a test run, the framework executes the chosen test methods in your derived classes. The test methods are run independently, with common setup and/or tear-down behaviour defined in the class, as shown below. + +```python +class YourTestClass(TestCase): + + def setUp(self): + #Setup run before every test method. + pass + + def tearDown(self): + #Clean up run after every test method. + pass + + def test_something_that_will_pass(self): + self.assertFalse(False) + + def test_something_that_will_fail(self): + self.assertTrue(False) +``` + +The best base class for most tests is [django.test.TestCase](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#testcase). This test class creates a clean database before its tests are run, and runs every test function in its own transaction. The class also owns a test [Client](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.Client) that you can use to simulate a user interacting with the code at the view level. In the following sections we're going to concentrate on unit tests, created using this [TestCase](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#testcase) base class. + +> **備註:** The [django.test.TestCase](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#testcase) class is very convenient, but may result in some tests being slower than they need to be (not every test will need to set up its own database or simulate the view interaction). Once you're familiar with what you can do with this class, you may want to replace some of your tests with the available simpler test classes. + +### What should you test? + +You should test all aspects of your own code, but not any libraries or functionality provided as part of Python or Django. + +So for example, consider the `Author` model defined below. You don't need to explicitly test that `first_name` and `last_name` have been stored properly as `CharField` in the database because that is something defined by Django (though of course in practice you will inevitably test this functionality during development). Nor do you need to test that the `date_of_birth` has been validated to be a date field, because that is again something implemented in Django. + +However you should check the text used for the labels (_First name, Last_name, Date of birth, Died_), and the size of the field allocated for the text (_100 chars_), because these are part of your design and something that could be broken/changed in future. + +```python +class Author(models.Model): + first_name = models.CharField(max_length=100) + last_name = models.CharField(max_length=100) + date_of_birth = models.DateField(null=True, blank=True) + date_of_death = models.DateField('Died', null=True, blank=True) + + def get_absolute_url(self): + return reverse('author-detail', args=[str(self.id)]) + + def __str__(self): + return '%s, %s' % (self.last_name, self.first_name) +``` + +Similarly, you should check that the custom methods `get_absolute_url()` and `__str__()` behave as required because they are your code/business logic. In the case of `get_absolute_url()` you can trust that the Django `reverse()` method has been implemented properly, so what you're testing is that the associated view has actually been defined. + +> **備註:** Astute readers may note that we would also want to constrain the date of birth and death to sensible values, and check that death comes after birth. In Django this constraint would be added to your form classes (although you can define validators for the fields these appear to only be used at the form level, not the model level). + +With that in mind lets start looking at how to define and run tests. + +## Test structure overview + +Before we go into the detail of "what to test", let's first briefly look at _where_ and _how_ tests are defined. + +Django uses the unittest module’s [built-in test discovery](https://docs.python.org/3/library/unittest.html#unittest-test-discovery), which will discover tests under the current working directory in any file named with the pattern **test\*.py**. Provided you name the files appropriately, you can use any structure you like. We recommend that you create a module for your test code, and have separate files for models, views, forms, and any other types of code you need to test. For example: + + catalog/ + /tests/ + __init__.py + test_models.py + test_forms.py + test_views.py + +Create a file structure as shown above in your _LocalLibrary_ project. The **\_\_init\_\_.py** should be an empty file (this tells Python that the directory is a package). You can create the three test files by copying and renaming the skeleton test file **/catalog/tests.py**. + +> **備註:** The skeleton test file **/catalog/tests.py** was created automatically when we [built the Django skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website). It is perfectly "legal" to put all your tests inside it, but if you test properly, you'll quickly end up with a very large and unmanageable test file. +> +> Delete the skeleton file as we won't need it. + +Open **/catalog/tests/test_models.py**. The file should import `django.test.TestCase`, as shown: + +```python +from django.test import TestCase + +# Create your tests here. +``` + +Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality. In other cases you may wish to have a separate class for testing a specific use case, with individual test functions that test aspects of that use-case (for example, a class to test that a model field is properly validated, with functions to test each of the possible failure cases). Again, the structure is very much up to you, but it is best if you are consistent. + +Add the test class below to the bottom of the file. The class demonstrates how to construct a test case class by deriving from `TestCase`. + +```python +class YourTestClass(TestCase): + + @classmethod + def setUpTestData(cls): + print("setUpTestData: Run once to set up non-modified data for all class methods.") + pass + + def setUp(self): + print("setUp: Run once for every test method to setup clean data.") + pass + + def test_false_is_false(self): + print("Method: test_false_is_false.") + self.assertFalse(False) + + def test_false_is_true(self): + print("Method: test_false_is_true.") + self.assertTrue(False) + + def test_one_plus_one_equals_two(self): + print("Method: test_one_plus_one_equals_two.") + self.assertEqual(1 + 1, 2) +``` + +The new class defines two methods that you can use for pre-test configuration (for example, to create any models or other objects you will need for the test): + +- `setUpTestData()` is called once at the beginning of the test run for class-level setup. You'd use this to create objects that aren't going to be modified or changed in any of the test methods. +- `setUp()` is called before every test function to set up any objects that may be modified by the test (every test function will get a "fresh" version of these objects). + +> **備註:** The test classes also have a `tearDown()` method which we haven't used. This method isn't particularly useful for database tests, since the `TestCase` base class takes care of database teardown for you. + +Below those we have a number of test methods, which use `Assert` functions to test whether conditions are true, false or equal (`AssertTrue`, `AssertFalse`, `AssertEqual`). If the condition does not evaluate as expected then the test will fail and report the error to your console. + +The `AssertTrue`, `AssertFalse`, `AssertEqual` are standard assertions provided by **unittest**. There are other standard assertions in the framework, and also [Django-specific assertions](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#assertions) to test if a view redirects (`assertRedirects`), to test if a particular template has been used (`assertTemplateUsed`), etc. + +> **備註:** You should **not** normally include **print()** functions in your tests as shown above. We do that here only so that you can see the order that the setup functions are called in the console (in the following section). + +## How to run the tests + +The easiest way to run all the tests is to use the command: + +```bash +python3 manage.py test +``` + +This will discover all files named with the pattern **test\*.py** under the current directory and run all tests defined using appropriate base classes (here we have a number of test files, but only **/catalog/tests/test_models.py** currently contains any tests.) By default the tests will individually report only on test failures, followed by a test summary. + +> **備註:** If you get errors similar to: `ValueError: Missing staticfiles manifest entry ...` this may be because testing does not run _collectstatic_ by default and your app is using a storage class that requires it (see [manifest_strict](https://docs.djangoproject.com/en/2.0/ref/contrib/staticfiles/#django.contrib.staticfiles.storage.ManifestStaticFilesStorage.manifest_strict) for more information). There are a number of ways you can overcome this problem - the easiest is to simply run _collectstatic_ before running the tests: +> +> ```bash +> python3 manage.py collectstatic +> ``` + +Run the tests in the root directory of _LocalLibrary_. You should see an output like the one below. + +```bash +>python3 manage.py test + +Creating test database for alias 'default'... +setUpTestData: Run once to set up non-modified data for all class methods. +setUp: Run once for every test method to setup clean data. +Method: test_false_is_false. +.setUp: Run once for every test method to setup clean data. +Method: test_false_is_true. +FsetUp: Run once for every test method to setup clean data. +Method: test_one_plus_one_equals_two. +. +====================================================================== +FAIL: test_false_is_true (catalog.tests.tests_models.YourTestClass) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "D:\Github\django_tmp\library_w_t_2\locallibrary\catalog\tests\tests_models.py", line 22, in test_false_is_true + self.assertTrue(False) +AssertionError: False is not true + +---------------------------------------------------------------------- +Ran 3 tests in 0.075s + +FAILED (failures=1) +Destroying test database for alias 'default'... +``` + +Here we see that we had one test failure, and we can see exactly what function failed and why (this failure is expected, because `False` is not `True`!). + +> **備註:** The most important thing to learn from the test output above is that it is much more valuable if you use descriptive/informative names for your objects and methods. + +The text shown in **bold** above would not normally appear in the test output (this is generated by the `print()` functions in our tests). This shows how the `setUpTestData()` method is called once for the class and `setUp()` is called before each method. + +The next sections show how you can run specific tests, and how to control how much information the tests display. + +### Showing more test information + +If you want to get more information about the test run you can change the _verbosity_. For example, to list the test successes as well as failures (and a whole bunch of information about how the testing database is set up) you can set the verbosity to "2" as shown: + +```bash +python3 manage.py test --verbosity 2 +``` + +The allowed verbosity levels are 0, 1, 2, and 3, with the default being "1". + +### Running specific tests + +If you want to run a subset of your tests you can do so by specifying the full dot path to the package(s), module, `TestCase` subclass or method: + +```bash +python3 manage.py test catalog.tests # Run the specified module +python3 manage.py test catalog.tests.test_models # Run the specified module +python3 manage.py test catalog.tests.test_models.YourTestClass # Run the specified class +python3 manage.py test catalog.tests.test_models.YourTestClass.test_one_plus_one_equals_two # Run the specified method +``` + +## LocalLibrary tests + +Now we know how to run our tests and what sort of things we need to test, let's look at some practical examples. + +> **備註:** We won't write every possible test, but this should give you and idea of how tests work, and what more you can do. + +### Models + +As discussed above, we should test anything that is part of our design or that is defined by code that we have written, but not libraries/code that is already tested by Django or the Python development team. + +For example, consider the `Author` model below. Here we should test the labels for all the fields, because even though we haven't explicitly specified most of them, we have a design that says what these values should be. If we don't test the values, then we don't know that the field labels have their intended values. Similarly while we trust that Django will create a field of the specified length, it is worthwhile to specify a test for this length to ensure that it was implemented as planned. + +```python +class Author(models.Model): + first_name = models.CharField(max_length=100) + last_name = models.CharField(max_length=100) + date_of_birth = models.DateField(null=True, blank=True) + date_of_death = models.DateField('Died', null=True, blank=True) + + def get_absolute_url(self): + return reverse('author-detail', args=[str(self.id)]) + + def __str__(self): + return '%s, %s' % (self.last_name, self.first_name) +``` + +Open our **/catalog/tests/test_models.py**, and replace any existing code with the following test code for the `Author` model. + +Here you'll see that we first import `TestCase` and derive our test class (`AuthorModelTest`) from it, using a descriptive name so we can easily identify any failing tests in the test output. We then call `setUpTestData()` to create an author object that we will use but not modify in any of the tests. + +```python +from django.test import TestCase + +# Create your tests here. + +from catalog.models import Author + +class AuthorModelTest(TestCase): + + @classmethod + def setUpTestData(cls): + #Set up non-modified objects used by all test methods + Author.objects.create(first_name='Big', last_name='Bob') + + def test_first_name_label(self): + author=Author.objects.get(id=1) + field_label = author._meta.get_field('first_name').verbose_name + self.assertEquals(field_label,'first name') + + def test_date_of_death_label(self): + author=Author.objects.get(id=1) + field_label = author._meta.get_field('date_of_death').verbose_name + self.assertEquals(field_label,'died') + + def test_first_name_max_length(self): + author=Author.objects.get(id=1) + max_length = author._meta.get_field('first_name').max_length + self.assertEquals(max_length,100) + + def test_object_name_is_last_name_comma_first_name(self): + author=Author.objects.get(id=1) + expected_object_name = '%s, %s' % (author.last_name, author.first_name) + self.assertEquals(expected_object_name,str(author)) + + def test_get_absolute_url(self): + author=Author.objects.get(id=1) + #This will also fail if the urlconf is not defined. + self.assertEquals(author.get_absolute_url(),'/catalog/author/1') +``` + +The field tests check that the values of the field labels (`verbose_name`) and that the size of the character fields are as expected. These methods all have descriptive names, and follow the same pattern: + +```python +author=Author.objects.get(id=1) # Get an author object to test +field_label = author._meta.get_field('first_name').verbose_name # Get the metadata for the required field and use it to query the required field data +self.assertEquals(field_label,'first name') # Compare the value to the expected result +``` + +The interesting things to note are: + +- We can't get the `verbose_name` directly using `author.first_name.verbose_name`, because `author.first_name` is a _string_ (not a handle to the `first_name` object that we can use to access its properties). Instead we need to use the author's `_meta` attribute to get an instance of the field and use that to query for the additional information. +- We chose to use `assertEquals(field_label,'first name')` rather than `assertTrue(field_label == 'first name')`. The reason for this is that if the test fails the output for the former tells you what the label actually was, which makes debugging the problem just a little easier. + +> **備註:** Tests for the `last_name` and `date_of_birth` labels, and also the test for the length of the `last_name` field have been omitted. Add your own versions now, following the naming conventions and approaches shown above. + +We also need to test our custom methods. These essentially just check that the object name was constructed as we expected using "Last Name", "First Name" format, and that the URL we get for an `Author` item is as we would expect. + +```python +def test_object_name_is_last_name_comma_first_name(self): + author=Author.objects.get(id=1) + expected_object_name = '%s, %s' % (author.last_name, author.first_name) + self.assertEquals(expected_object_name,str(author)) + +def test_get_absolute_url(self): + author=Author.objects.get(id=1) + #This will also fail if the urlconf is not defined. + self.assertEquals(author.get_absolute_url(),'/catalog/author/1') +``` + +Run the tests now. If you created the Author model as we described in the models tutorial it is quite likely that you will get an error for the `date_of_death` label as shown below. The test is failing because it was written expecting the label definition to follow Django's convention of not capitalising the first letter of the label (Django does this for you). + +```bash +====================================================================== +FAIL: test_date_of_death_label (catalog.tests.test_models.AuthorModelTest) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "D:\...\locallibrary\catalog\tests\test_models.py", line 32, in test_date_of_death_label + self.assertEquals(field_label,'died') +AssertionError: 'Died' != 'died' +- Died +? ^ ++ died +? ^ +``` + +This is a very minor bug, but it does highlight how writing tests can more thoroughly check any assumptions you may have made. + +> **備註:** Change the label for the date_of_death field (/catalog/models.py) to "died" and re-run the tests. + +The patterns for testing the other models are similar so we won't continue to discuss these further. Feel free to create your own tests for the our other models. + +### Forms + +The philosophy for testing your forms is the same as for testing your models; you need to test anything that you've coded or your design specifies, but not the behaviour of the underlying framework and other third party libraries. + +Generally this means that you should test that the forms have the fields that you want, and that these are displayed with appropriate labels and help text. You don't need to verify that Django validates the field type correctly (unless you created your own custom field and validation) — i.e. you don't need to test that an email field only accepts emails. However you would need to test any additional validation that you expect to be performed on the fields and any messages that your code will generate for errors. + +Consider our form for renewing books. This has just one field for the renewal date, which will have a label and help text that we will need to verify. + +```python +class RenewBookForm(forms.Form): + """ + Form for a librarian to renew books. + """ + renewal_date = forms.DateField(help_text="Enter a date between now and 4 weeks (default 3).") + + def clean_renewal_date(self): + data = self.cleaned_data['renewal_date'] + + #Check date is not in past. + if data < datetime.date.today(): + raise ValidationError(_('Invalid date - renewal in past')) + #Check date is in range librarian allowed to change (+4 weeks) + if data > datetime.date.today() + datetime.timedelta(weeks=4): + raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead')) + + # Remember to always return the cleaned data. + return data +``` + +Open our **/catalog/tests/test_forms.py** file and replace any existing code with the following test code for the `RenewBookForm` form. We start by importing our form and some Python and Django libraries to help test time-related functionality. We then declare our form test class in the same way as we did for models, using a descriptive name for our `TestCase`-derived test class. + +```python +from django.test import TestCase + +# Create your tests here. + +import datetime +from django.utils import timezone +from catalog.forms import RenewBookForm + +class RenewBookFormTest(TestCase): + + def test_renew_form_date_field_label(self): + form = RenewBookForm() + self.assertTrue(form.fields['renewal_date'].label == None or form.fields['renewal_date'].label == 'renewal date') + + def test_renew_form_date_field_help_text(self): + form = RenewBookForm() + self.assertEqual(form.fields['renewal_date'].help_text,'Enter a date between now and 4 weeks (default 3).') + + def test_renew_form_date_in_past(self): + date = datetime.date.today() - datetime.timedelta(days=1) + form_data = {'renewal_date': date} + form = RenewBookForm(data=form_data) + self.assertFalse(form.is_valid()) + + def test_renew_form_date_too_far_in_future(self): + date = datetime.date.today() + datetime.timedelta(weeks=4) + datetime.timedelta(days=1) + form_data = {'renewal_date': date} + form = RenewBookForm(data=form_data) + self.assertFalse(form.is_valid()) + + def test_renew_form_date_today(self): + date = datetime.date.today() + form_data = {'renewal_date': date} + form = RenewBookForm(data=form_data) + self.assertTrue(form.is_valid()) + + def test_renew_form_date_max(self): + date = timezone.now() + datetime.timedelta(weeks=4) + form_data = {'renewal_date': date} + form = RenewBookForm(data=form_data) + self.assertTrue(form.is_valid()) +``` + +The first two functions test that the field's `label` and `help_text` are as expected. We have to access the field using the fields dictionary (e.g. `form.fields['renewal_date']`). Note here that we also have to test whether the label value is `None`, because even though Django will render the correct label it returns `None` if the value is not _explicitly_ set. + +The rest of the functions test that the form is valid for renewal dates just inside the acceptable range and invalid for values outside the range. Note how we construct test date values around our current date (`datetime.date.today()`) using `datetime.timedelta()` (in this case specifying a number of days or weeks). We then just create the form, passing in our data, and test if it is valid. + +> **備註:** Here we don't actually use the database or test client. Consider modifying these tests to use [SimpleTestCase](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.SimpleTestCase). +> +> We also need to validate that the correct errors are raised if the form is invalid, however this is usually done as part of view processing, so we'll take care of that in the next section. + +That's all for forms; we do have some others, but they are automatically created by our generic class-based editing views, and should be tested there! Run the tests and confirm that our code still passes! + +### Views + +To validate our view behaviour we use the Django test [Client](https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.Client). This class acts like a dummy web browser that we can use to simulate `GET` and `POST` requests on a URL and observe the response. We can see almost everything about the response, from low-level HTTP (result headers and status codes) through to the template we're using to render the HTML and the context data we're passing to it. We can also see the chain of redirects (if any) and check the URL and status code at each step. This allows us to verify that each view is doing what is expected. + +Let's start with one of our simplest views, which provides a list of all Authors. This is displayed at URL **/catalog/authors/** (an URL named 'authors' in the URL configuration). + +```python +class AuthorListView(generic.ListView): + model = Author + paginate_by = 10 +``` + +As this is a generic list view almost everything is done for us by Django. Arguably if you trust Django then the only thing you need to test is that the view is accessible at the correct URL and can be accessed using its name. However if you're using a test-driven development process you'll start by writing tests that confirm that the view displays all Authors, paginating them in lots of 10. + +Open the **/catalog/tests/test_views.py** file and replace any existing text with the following test code for `AuthorListView`. As before we import our model and some useful classes. In the `setUpTestData()` method we set up a number of `Author` objects so that we can test our pagination. + +```python +from django.test import TestCase + +# Create your tests here. + +from catalog.models import Author +from django.urls import reverse + +class AuthorListViewTest(TestCase): + + @classmethod + def setUpTestData(cls): + #Create 13 authors for pagination tests + number_of_authors = 13 + for author_num in range(number_of_authors): + Author.objects.create(first_name='Christian %s' % author_num, last_name = 'Surname %s' % author_num,) + + def test_view_url_exists_at_desired_location(self): + resp = self.client.get('/catalog/authors/') + self.assertEqual(resp.status_code, 200) + + def test_view_url_accessible_by_name(self): + resp = self.client.get(reverse('authors')) + self.assertEqual(resp.status_code, 200) + + def test_view_uses_correct_template(self): + resp = self.client.get(reverse('authors')) + self.assertEqual(resp.status_code, 200) + + self.assertTemplateUsed(resp, 'catalog/author_list.html') + + def test_pagination_is_ten(self): + resp = self.client.get(reverse('authors')) + self.assertEqual(resp.status_code, 200) + self.assertTrue('is_paginated' in resp.context) + self.assertTrue(resp.context['is_paginated'] == True) + self.assertTrue( len(resp.context['author_list']) == 10) + + def test_lists_all_authors(self): + #Get second page and confirm it has (exactly) remaining 3 items + resp = self.client.get(reverse('authors')+'?page=2') + self.assertEqual(resp.status_code, 200) + self.assertTrue('is_paginated' in resp.context) + self.assertTrue(resp.context['is_paginated'] == True) + self.assertTrue( len(resp.context['author_list']) == 3) +``` + +All the tests use the client (belonging to our `TestCase`'s derived class) to simulate a `GET` request and get a response (`resp`). The first version checks a specific URL (note, just the specific path without the domain) while the second generates the URL from its name in the URL configuration. + +```python +resp = self.client.get('/catalog/authors/') +resp = self.client.get(reverse('authors')) +``` + +Once we have the response we query it for its status code, the template used, whether or not the response is paginated, the number of items returned, and the total number of items. + +The most interesting variable we demonstrate above is `resp.context`, which is the context variable passed to the template by the view. This is incredibly useful for testing, because it allows us to confirm that our template is getting all the data it needs. In other words we can check that we're using the intended template and what data the template is getting, which goes a long way to verifying that any rendering issues are solely due to template. + +#### Views that are restricted to logged in users + +In some cases you'll want to test a view that is restricted to just logged in users. For example our `LoanedBooksByUserListView` is very similar to our previous view but is only available to logged in users, and only displays `BookInstance` records that are borrowed by the current user, have the 'on loan' status, and are ordered "oldest first". + +```python +from django.contrib.auth.mixins import LoginRequiredMixin + +class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView): + """ + Generic class-based view listing books on loan to current user. + """ + model = BookInstance + template_name ='catalog/bookinstance_list_borrowed_user.html' + paginate_by = 10 + + def get_queryset(self): + return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back') +``` + +Add the following test code to **/catalog/tests/test_views.py**. Here we first use `SetUp()` to create some user login accounts and `BookInstance` objects (along with their associated books and other records) that we'll use later in the tests. Half of the books are borrowed by each test user, but we've initially set the status of all books to "maintenance". We've used `SetUp()` rather than `setUpTestData()` because we'll be modifying some of these objects later. + +> **備註:** The `setUp()` code below creates a book with a specified `Language`, but _your_ code may not include the `Language` model as this was created as a _challenge_. If this is the case, simply comment out the parts of the code that create or import Language objects. You should also do this in the `RenewBookInstancesViewTest` section that follows. + +```python +import datetime +from django.utils import timezone + +from catalog.models import BookInstance, Book, Genre, Language +from django.contrib.auth.models import User #Required to assign User as a borrower + +class LoanedBookInstancesByUserListViewTest(TestCase): + + def setUp(self): + #Create two users + test_user1 = User.objects.create_user(username='testuser1', password='12345') + test_user1.save() + test_user2 = User.objects.create_user(username='testuser2', password='12345') + test_user2.save() + + #Create a book + test_author = Author.objects.create(first_name='John', last_name='Smith') + test_genre = Genre.objects.create(name='Fantasy') + test_language = Language.objects.create(name='English') + test_book = Book.objects.create(title='Book Title', summary = 'My book summary', isbn='ABCDEFG', author=test_author, language=test_language) + # Create genre as a post-step + genre_objects_for_book = Genre.objects.all() + test_book.genre.set(genre_objects_for_book) #Direct assignment of many-to-many types not allowed. + test_book.save() + + #Create 30 BookInstance objects + number_of_book_copies = 30 + for book_copy in range(number_of_book_copies): + return_date= timezone.now() + datetime.timedelta(days=book_copy%5) + if book_copy % 2: + the_borrower=test_user1 + else: + the_borrower=test_user2 + status='m' + BookInstance.objects.create(book=test_book,imprint='Unlikely Imprint, 2016', due_back=return_date, borrower=the_borrower, status=status) + + def test_redirect_if_not_logged_in(self): + resp = self.client.get(reverse('my-borrowed')) + self.assertRedirects(resp, '/accounts/login/?next=/catalog/mybooks/') + + def test_logged_in_uses_correct_template(self): + login = self.client.login(username='testuser1', password='12345') + resp = self.client.get(reverse('my-borrowed')) + + #Check our user is logged in + self.assertEqual(str(resp.context['user']), 'testuser1') + #Check that we got a response "success" + self.assertEqual(resp.status_code, 200) + + #Check we used correct template + self.assertTemplateUsed(resp, 'catalog/bookinstance_list_borrowed_user.html') +``` + +To verify that the view will redirect to a login page if the user is not logged in we use `assertRedirects`, as demonstrated in `test_redirect_if_not_logged_in()`. To verify that the page is displayed for a logged in user we first log in our test user, and then access the page again and check that we get a `status_code` of 200 (success). + +The rest of the tests verify that our view only returns books that are on loan to our current borrower. Copy the (self-explanatory) code at the end of the test class above. + +```python + def test_only_borrowed_books_in_list(self): + login = self.client.login(username='testuser1', password='12345') + resp = self.client.get(reverse('my-borrowed')) + + #Check our user is logged in + self.assertEqual(str(resp.context['user']), 'testuser1') + #Check that we got a response "success" + self.assertEqual(resp.status_code, 200) + + #Check that initially we don't have any books in list (none on loan) + self.assertTrue('bookinstance_list' in resp.context) + self.assertEqual( len(resp.context['bookinstance_list']),0) + + #Now change all books to be on loan + get_ten_books = BookInstance.objects.all()[:10] + + for copy in get_ten_books: + copy.status='o' + copy.save() + + #Check that now we have borrowed books in the list + resp = self.client.get(reverse('my-borrowed')) + #Check our user is logged in + self.assertEqual(str(resp.context['user']), 'testuser1') + #Check that we got a response "success" + self.assertEqual(resp.status_code, 200) + + self.assertTrue('bookinstance_list' in resp.context) + + #Confirm all books belong to testuser1 and are on loan + for bookitem in resp.context['bookinstance_list']: + self.assertEqual(resp.context['user'], bookitem.borrower) + self.assertEqual('o', bookitem.status) + + def test_pages_ordered_by_due_date(self): + + #Change all books to be on loan + for copy in BookInstance.objects.all(): + copy.status='o' + copy.save() + + login = self.client.login(username='testuser1', password='12345') + resp = self.client.get(reverse('my-borrowed')) + + #Check our user is logged in + self.assertEqual(str(resp.context['user']), 'testuser1') + #Check that we got a response "success" + self.assertEqual(resp.status_code, 200) + + #Confirm that of the items, only 10 are displayed due to pagination. + self.assertEqual( len(resp.context['bookinstance_list']),10) + + last_date=0 + for copy in resp.context['bookinstance_list']: + if last_date==0: + last_date=copy.due_back + else: + self.assertTrue(last_date <= copy.due_back) +``` + +You could also add pagination tests, should you so wish! + +#### Testing views with forms + +Testing views with forms is a little more complicated than in the cases above, because you need to test more code paths: initial display, display after data validation has failed, and display after validation has succeeded. The good news is that we use the client for testing in almost exactly the same way as we did for display-only views. + +To demonstrate, let's write some tests for the view used to renew books (`renew_book_librarian()`): + +```python +from .forms import RenewBookForm + +@permission_required('catalog.can_mark_returned') +def renew_book_librarian(request, pk): + """ + View function for renewing a specific BookInstance by librarian + """ + book_inst=get_object_or_404(BookInstance, pk = pk) + + # If this is a POST request then process the Form data + if request.method == 'POST': + + # Create a form instance and populate it with data from the request (binding): + form = RenewBookForm(request.POST) + + # Check if the form is valid: + if form.is_valid(): + # process the data in form.cleaned_data as required (here we just write it to the model due_back field) + book_inst.due_back = form.cleaned_data['renewal_date'] + book_inst.save() + + # redirect to a new URL: + return HttpResponseRedirect(reverse('all-borrowed') ) + + # If this is a GET (or any other method) create the default form + else: + proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3) + form = RenewBookForm(initial={'renewal_date': proposed_renewal_date,}) + + return render(request, 'catalog/book_renew_librarian.html', {'form': form, 'bookinst':book_inst}) +``` + +We'll need to test that the view is only available to users who have the `can_mark_returned `permission, and that users are redirected to an HTTP 404 error page if they attempt to renew a `BookInstance` that does not exist. We should check that the initial value of the form is seeded with a date three weeks in the future, and that if validation succeeds we're redirected to the "all-borrowed books" view. As part of checking the validation-fail tests we'll also check that our form is sending the appropriate error messages. + +Add the first part of the test class (shown below) to the bottom of **/catalog/tests/test_views.py**. This creates two users and two book instances, but only gives one user the permission required to access the view. The code to grant permissions during tests is shown in bold: + +```python +from django.contrib.auth.models import Permission # Required to grant the permission needed to set a book as returned. + +class RenewBookInstancesViewTest(TestCase): + + def setUp(self): + #Create a user + test_user1 = User.objects.create_user(username='testuser1', password='12345') + test_user1.save() + + test_user2 = User.objects.create_user(username='testuser2', password='12345') + test_user2.save() + permission = Permission.objects.get(name='Set book as returned') + test_user2.user_permissions.add(permission) + test_user2.save() + + #Create a book + test_author = Author.objects.create(first_name='John', last_name='Smith') + test_genre = Genre.objects.create(name='Fantasy') + test_language = Language.objects.create(name='English') + test_book = Book.objects.create(title='Book Title', summary = 'My book summary', isbn='ABCDEFG', author=test_author, language=test_language,) + # Create genre as a post-step + genre_objects_for_book = Genre.objects.all() + test_book.genre.set(genre_objects_for_book) # Direct assignment of many-to-many types not allowed. + test_book.save() + + #Create a BookInstance object for test_user1 + return_date= datetime.date.today() + datetime.timedelta(days=5) + self.test_bookinstance1=BookInstance.objects.create(book=test_book,imprint='Unlikely Imprint, 2016', due_back=return_date, borrower=test_user1, status='o') + + #Create a BookInstance object for test_user2 + return_date= datetime.date.today() + datetime.timedelta(days=5) + self.test_bookinstance2=BookInstance.objects.create(book=test_book,imprint='Unlikely Imprint, 2016', due_back=return_date, borrower=test_user2, status='o') +``` + +Add the following tests to the bottom of the test class. These check that only users with the correct permissions (_testuser2_) can access the view. We check all the cases: when the user is not logged in, when a user is logged in but does not have the correct permissions, when the user has permissions but is not the borrower (should succeed), and what happens when they try to access a `BookInstance` that doesn't exist. We also check that the correct template is used. + +```python + def test_redirect_if_not_logged_in(self): + resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) ) + #Manually check redirect (Can't use assertRedirect, because the redirect URL is unpredictable) + self.assertEqual( resp.status_code,302) + self.assertTrue( resp.url.startswith('/accounts/login/') ) + + def test_redirect_if_logged_in_but_not_correct_permission(self): + login = self.client.login(username='testuser1', password='12345') + resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) ) + + #Manually check redirect (Can't use assertRedirect, because the redirect URL is unpredictable) + self.assertEqual( resp.status_code,302) + self.assertTrue( resp.url.startswith('/accounts/login/') ) + + def test_logged_in_with_permission_borrowed_book(self): + login = self.client.login(username='testuser2', password='12345') + resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance2.pk,}) ) + + #Check that it lets us login - this is our book and we have the right permissions. + self.assertEqual( resp.status_code,200) + + def test_logged_in_with_permission_another_users_borrowed_book(self): + login = self.client.login(username='testuser2', password='12345') + resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) ) + + #Check that it lets us login. We're a librarian, so we can view any users book + self.assertEqual( resp.status_code,200) + + def test_HTTP404_for_invalid_book_if_logged_in(self): + import uuid + test_uid = uuid.uuid4() #unlikely UID to match our bookinstance! + login = self.client.login(username='testuser2', password='12345') + resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':test_uid,}) ) + self.assertEqual( resp.status_code,404) + + def test_uses_correct_template(self): + login = self.client.login(username='testuser2', password='12345') + resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) ) + self.assertEqual( resp.status_code,200) + + #Check we used correct template + self.assertTemplateUsed(resp, 'catalog/book_renew_librarian.html') +``` + +Add the next test method, as shown below. This checks that the initial date for the form is three weeks in the future. Note how we are able to access the value of the initial value of the form field (shown in bold). + +```python + def test_form_renewal_date_initially_has_date_three_weeks_in_future(self): + login = self.client.login(username='testuser2', password='12345') + resp = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}) ) + self.assertEqual( resp.status_code,200) + + date_3_weeks_in_future = datetime.date.today() + datetime.timedelta(weeks=3) + self.assertEqual(resp.context['form'].initial['renewal_date'], date_3_weeks_in_future ) +``` + +The next test (add this to the class too) checks that the view redirects to a list of all borrowed books if renewal succeeds. What differs here is that for the first time we show how you can `POST` data using the client. The post _data_ is the second argument to the post function, and is specified as a dictionary of key/values. + +```python + def test_redirects_to_all_borrowed_book_list_on_success(self): + login = self.client.login(username='testuser2', password='12345') + valid_date_in_future = datetime.date.today() + datetime.timedelta(weeks=2) + resp = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal_date':valid_date_in_future} ) + self.assertRedirects(resp, reverse('all-borrowed') ) +``` + +> **警告:** The _all-borrowed_ view was added as a _challenge_, and your code may instead redirect to the home page '/'. If so, modify the last two lines of the test code to be like the code below. The `follow=True` in the request ensures that the request returns the final destination URL (hence checking `/catalog/` rather than `/`). +> +> ```python +> resp = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal_date':valid_date_in_future},follow=True ) +> self.assertRedirects(resp, '/catalog/') +> ``` + +Copy the last two functions into the class, as seen below. These again test `POST` requests, but in this case with invalid renewal dates. We use `assertFormError() `to verify that the error messages are as expected. + +```python + def test_form_invalid_renewal_date_past(self): + login = self.client.login(username='testuser2', password='12345') + date_in_past = datetime.date.today() - datetime.timedelta(weeks=1) + resp = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal_date':date_in_past} ) + self.assertEqual( resp.status_code,200) + self.assertFormError(resp, 'form', 'renewal_date', 'Invalid date - renewal in past') + + def test_form_invalid_renewal_date_future(self): + login = self.client.login(username='testuser2', password='12345') + invalid_date_in_future = datetime.date.today() + datetime.timedelta(weeks=5) + resp = self.client.post(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance1.pk,}), {'renewal_date':invalid_date_in_future} ) + self.assertEqual( resp.status_code,200) + self.assertFormError(resp, 'form', 'renewal_date', 'Invalid date - renewal more than 4 weeks ahead') +``` + +The same sorts of techniques can be used to test the other view. + +### Templates + +Django provides test APIs to check that the correct template is being called by your views, and to allow you to verify that the correct information is being sent. There is however no specific API support for testing in Django that your HTML output is rendered as expected. + +## Other recommended test tools + +Django's test framework can help you write effective unit and integration tests — we've only scratched the surface of what the underlying **unittest** framework can do, let alone Django's additions (for example, check out how you can use [unittest.mock](https://docs.python.org/3.5/library/unittest.mock-examples.html) to patch third party libraries so you can more thoroughly test your own code). + +While there are numerous other test tools that you can use, we'll just highlight two: + +- [Coverage](http://coverage.readthedocs.io/en/latest/): This Python tool reports on how much of your code is actually executed by your tests. It is particularly useful when you're getting started, and you are trying to work out exactly what you should test. +- [Selenium](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Your_own_automation_environment) is a framework to automate testing in a real browser. It allows you to simulate a real user interacting with the site, and provides a great framework for system testing your site (the next step up from integration testing). + +## Challenge yourself + +There are a lot more models and views we can test. As a simple task, try to create a test case for the `AuthorCreate` view. + +```python +class AuthorCreate(PermissionRequiredMixin, CreateView): + model = Author + fields = '__all__' + initial={'date_of_death':'12/10/2016',} + permission_required = 'catalog.can_mark_returned' +``` + +Remember that you need to check anything that you specify or that is part of the design. This will include who has access, the initial date, the template used, and where the view redirects on success. + +## Summary + +Writing test code is neither fun nor glamorous, and is consequently often left to last (or not at all) when creating a website. It is however an essential part of making sure that your code is safe to release after making changes, and cost-effective to maintain. + +In this tutorial we've shown you how to write and run tests for your models, forms, and views. Most importantly we've provided a brief summary of what you should test, which is often the hardest thing to work out when you're getting started. There is a lot more to know, but even with what you've learned already you should be able to create effective unit tests for your websites. + +The next and final tutorial shows how you can deploy your wonderful (and fully tested!) Django website. + +## See also + +- [Writing and running tests](https://docs.djangoproject.com/en/2.0/topics/testing/overview/) (Django docs) +- [Writing your first Django app, part 5 > Introducing automated testing](https://docs.djangoproject.com/en/2.0/intro/tutorial05/) (Django docs) +- [Testing tools reference](https://docs.djangoproject.com/en/2.0/topics/testing/tools/) (Django docs) +- [Advanced testing topics](https://docs.djangoproject.com/en/2.0/topics/testing/advanced/) (Django docs) +- [A Guide to Testing in Django](http://toastdriven.com/blog/2011/apr/10/guide-to-testing-in-django/) (Toast Driven Blog, 2011) +- [Workshop: Test-Driven Web Development with Django](http://test-driven-django-development.readthedocs.io/en/latest/index.html) (San Diego Python, 2014) +- [Testing in Django (Part 1) - Best Practices and Examples](https://realpython.com/blog/python/testing-in-django-part-1-best-practices-and-examples/) (RealPython, 2013) + +{{PreviousMenuNext("Learn/Server-side/Django/Forms", "Learn/Server-side/Django/Deployment", "Learn/Server-side/Django")}} + +## In this module + +- [Django introduction](/en-US/docs/Learn/Server-side/Django/Introduction) +- [Setting up a Django development environment](/en-US/docs/Learn/Server-side/Django/development_environment) +- [Django Tutorial: The Local Library website](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django Tutorial Part 2: Creating a skeleton website](/en-US/docs/Learn/Server-side/Django/skeleton_website) +- [Django Tutorial Part 3: Using models](/en-US/docs/Learn/Server-side/Django/Models) +- [Django Tutorial Part 4: Django admin site](/en-US/docs/Learn/Server-side/Django/Admin_site) +- [Django Tutorial Part 5: Creating our home page](/en-US/docs/Learn/Server-side/Django/Home_page) +- [Django Tutorial Part 6: Generic list and detail views](/en-US/docs/Learn/Server-side/Django/Generic_views) +- [Django Tutorial Part 7: Sessions framework](/en-US/docs/Learn/Server-side/Django/Sessions) +- [Django Tutorial Part 8: User authentication and permissions](/en-US/docs/Learn/Server-side/Django/Authentication) +- [Django Tutorial Part 9: Working with forms](/en-US/docs/Learn/Server-side/Django/Forms) +- [Django Tutorial Part 10: Testing a Django web application](/en-US/docs/Learn/Server-side/Django/Testing) +- [Django Tutorial Part 11: Deploying Django to production](/en-US/docs/Learn/Server-side/Django/Deployment) +- [Django web application security](/en-US/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django mini blog](/en-US/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/tutorial_local_library_website/index.html b/files/zh-tw/learn/server-side/django/tutorial_local_library_website/index.html deleted file mode 100644 index 0179acb69fd780..00000000000000 --- a/files/zh-tw/learn/server-side/django/tutorial_local_library_website/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: 'Django 教學 1: 本地圖書館網站' -slug: Learn/Server-side/Django/Tutorial_local_library_website -tags: - - django - - 初學者 -translation_of: Learn/Server-side/Django/Tutorial_local_library_website ---- -
    {{LearnSidebar}}
    - -
    {{PreviousMenuNext("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django")}}
    - -

    我們實戰教學系列的第一篇,會解釋你將學到什麼。並提供一個“本地圖書館” 的例子,作為概述。在接下來的教學裡,我們會不斷完善和改進這個網站。

    - - - - - - - - - - - - -
    前提:閱讀 Django 介紹。在接下來的文章裡,你需要創建 Django 開發環境.
    目標:介紹教學裡使用的網站應用,讓讀者明白要討論的主題。
    - -

    概覽

    - -

    歡迎來到 MDN 的 ”本地圖書館“ Django 教學。在教學裡,我們會開發一個網站,用來管理本地圖書館的目錄。

    - -

    在這一系列的教學裡,你將:

    - -
      -
    • 運用 Django 的工具,創建網站和應用的框架。
    • -
    • 啟動和停止開發用的服務器。
    • -
    • 創建模型(models)用來表示應用裡的數據。
    • -
    • 運用 Django 的 admin 網站,以填充網站數據。
    • -
    • 面對不同的網路請求,創建視圖函數(views)取回相應的數據。並把數據用模板(templates ),渲染成 HTML ,展示在瀏覽器裡。
    • -
    • 創建網路映射,將不同的 URL 模式,分發給特定的視圖函數(views)。
    • -
    • 添加用戶認證和會話(sessions),管理網站行為和進入權限。
    • -
    • 使用表單。
    • -
    • 為應用編寫測試。
    • -
    • 有效運用 Django 的安全系統。
    • -
    • 把應用佈置到生產環境中。
    • -
    - -

    關於這些主題,你已經學會了一些,並對其他的也有了簡單的了解。在這系列教學的最後,你會學到足夠多,而可以自己開發簡單的Django 應用了。

    - -

    本地圖書館網站

    - -

    本地圖書館,是我們在本系列教學裡,創建和不斷改善的網站。跟你期望的一樣,這個網站的目標,是為一個小型的圖書館,提供一個線上目錄。在這個小型圖書館裡,用戶能瀏覽書籍,和管理他們的帳號。

    - -

    這個例子是精心挑選出來的,因為它可以根據我們的需要,增加或多或少的細節。也能用來展示,幾乎所有的 Django 特性。更重要的是,它提供了一條指南式的路線,在這條路線中,我們會用到 Django 網路框架最重要的功能:

    - -
      -
    • 在第一篇教學裡,我們會定義一個,簡單到只能瀏覽的圖書館。圖書館的會員,可以查找哪些書可以借閱。我們得以探索那些,幾乎所有網站都會運用的操作:閱讀和展示數據庫裡的內容。
    • -
    • 接下來,圖書館會慢慢擴展,以展示更高級的 Django 特性。例如,我們會擴展功能,讓會員能夠保留圖書。這個特性會展示如何使用表單,並支持用戶認證。
    • -
    - -

    儘管這是一個非常容易擴展的例子,它被稱為本地圖書館是有原因的——我們希望用最少的訊息,幫助你快速創建、和運用 Django。最後,我們會存儲圖書訊息,圖書數量,作者和其他重要訊息。我們不會儲存圖書館可能會儲存的其他訊息,或是提供一個支持多個圖書館、或是 ”大型圖書館“ 功能的建構。

    - -

    我卡住了,從哪裡獲得源程式碼呢?

    - -

    在學習本系列教程時,我們會提供合適的代碼片段,你可以粘貼複製,但是有些代碼我們希望你能自己擴展(在提示下)。

    - -

    如果你卡在某個地方,你可以在 Github 裡找到網站的完整代碼。

    - -

    總結

    - -

    現在你對本地圖書館網站有了一些了解並知道你會學到什麼。是時候創建我們例子會用到的網站框架了。

    - -

    {{PreviousMenuNext("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django")}}

    - -

    本系列教學

    - - diff --git a/files/zh-tw/learn/server-side/django/tutorial_local_library_website/index.md b/files/zh-tw/learn/server-side/django/tutorial_local_library_website/index.md new file mode 100644 index 00000000000000..9766fbd308e286 --- /dev/null +++ b/files/zh-tw/learn/server-side/django/tutorial_local_library_website/index.md @@ -0,0 +1,85 @@ +--- +title: 'Django 教學 1: 本地圖書館網站' +slug: Learn/Server-side/Django/Tutorial_local_library_website +tags: + - django + - 初學者 +translation_of: Learn/Server-side/Django/Tutorial_local_library_website +--- +{{LearnSidebar}}{{PreviousMenuNext("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django")}} + +我們實戰教學系列的第一篇,會解釋你將學到什麼。並提供一個“本地圖書館” 的例子,作為概述。在接下來的教學裡,我們會不斷完善和改進這個網站。 + + + + + + + + + + + + +
    前提:閱讀 Django 介紹。在接下來的文章裡,你需要創建 Django 開發環境.
    目標:介紹教學裡使用的網站應用,讓讀者明白要討論的主題。
    + +## 概覽 + +歡迎來到 MDN 的 ”本地圖書館“ Django 教學。在教學裡,我們會開發一個網站,用來管理本地圖書館的目錄。 + +在這一系列的教學裡,你將: + +- 運用 Django 的工具,創建網站和應用的框架。 +- 啟動和停止開發用的服務器。 +- 創建模型(models)用來表示應用裡的數據。 +- 運用 Django 的 admin 網站,以填充網站數據。 +- 面對不同的網路請求,創建視圖函數(views)取回相應的數據。並把數據用模板(templates ),渲染成 HTML ,展示在瀏覽器裡。 +- 創建網路映射,將不同的 URL 模式,分發給特定的視圖函數(views)。 +- 添加用戶認證和會話(sessions),管理網站行為和進入權限。 +- 使用表單。 +- 為應用編寫測試。 +- 有效運用 Django 的安全系統。 +- 把應用佈置到生產環境中。 + +關於這些主題,你已經學會了一些,並對其他的也有了簡單的了解。在這系列教學的最後,你會學到足夠多,而可以自己開發簡單的 Django 應用了。 + +## 本地圖書館網站 + +本地圖書館,是我們在本系列教學裡,創建和不斷改善的網站。跟你期望的一樣,這個網站的目標,是為一個小型的圖書館,提供一個線上目錄。在這個小型圖書館裡,用戶能瀏覽書籍,和管理他們的帳號。 + +這個例子是精心挑選出來的,因為它可以根據我們的需要,增加或多或少的細節。也能用來展示,幾乎所有的 Django 特性。更重要的是,它提供了一條指南式的路線,在這條路線中,我們會用到 Django 網路框架最重要的功能: + +- 在第一篇教學裡,我們會定義一個,簡單到只能瀏覽的圖書館。圖書館的會員,可以查找哪些書可以借閱。我們得以探索那些,幾乎所有網站都會運用的操作:閱讀和展示數據庫裡的內容。 +- 接下來,圖書館會慢慢擴展,以展示更高級的 Django 特性。例如,我們會擴展功能,讓會員能夠保留圖書。這個特性會展示如何使用表單,並支持用戶認證。 + +儘管這是一個非常容易擴展的例子,它被稱為本地圖書館是有原因的——我們希望用最少的訊息,幫助你快速創建、和運用 Django。最後,我們會存儲圖書訊息,圖書數量,作者和其他重要訊息。我們不會儲存圖書館可能會儲存的其他訊息,或是提供一個支持多個圖書館、或是 ”大型圖書館“ 功能的建構。 + +## 我卡住了,從哪裡獲得源程式碼呢? + +在學習本系列教程時,我們會提供合適的代碼片段,你可以粘貼複製,但是有些代碼我們希望你能自己擴展(在提示下)。 + +如果你卡在某個地方,你可以在 [Github ](https://github.com/mdn/django-locallibrary-tutorial)裡找到網站的完整代碼。 + +## 總結 + +現在你對本地圖書館網站有了一些了解並知道你會學到什麼。是時候創建我們例子會用到的[網站框架](/zh-TW/docs/Learn/Server-side/Django/skeleton_website)了。 + +{{PreviousMenuNext("Learn/Server-side/Django/development_environment", "Learn/Server-side/Django/skeleton_website", "Learn/Server-side/Django")}} + +## 本系列教學 + +- [Django 介紹](/zh-TW/docs/Learn/Server-side/Django/Introduction) +- [設定 Django 開發環境](/zh-TW/docs/Learn/Server-side/Django/development_environment) +- [Django 教學: 本地圖書館網站](/zh-TW/docs/Learn/Server-side/Django/Tutorial_local_library_website) +- [Django 教學 第 2 部分: 建立網站骨架](/zh-TW/docs/Learn/Server-side/Django/skeleton_website) +- [Django 教學 第 3 部分: 使用模型](/zh-TW/docs/Learn/Server-side/Django/Models) +- [Django 教學 第 4 部分: Django 的管理員頁面](/zh-TW/docs/Learn/Server-side/Django/Admin_site) +- [Django 教學 第 5 部分: 創建我們的首頁](/zh-TW/docs/Learn/Server-side/Django/Home_page) +- [Django 教學 第 6 部分: 通用列表與詳細視圖](/zh-TW/docs/Learn/Server-side/Django/Generic_views) +- [Django 教學 第 7 部分: 會話 (Sessions) 框架](/zh-TW/docs/Learn/Server-side/Django/Sessions) +- [Django 教學 第 8 部分: 使用者的身分驗證與權限](/zh-TW/docs/Learn/Server-side/Django/Authentication) +- [Django 教學 第 9 部分: 使用表單](/zh-TW/docs/Learn/Server-side/Django/Forms) +- [Django 教學 第 10 部分: 測試 Django 網頁應用](/zh-TW/docs/Learn/Server-side/Django/Testing) +- [Django 教學 第 11 部分: 部署 Django 到生產環境(production)](/zh-TW/docs/Learn/Server-side/Django/Deployment) +- [Django 網頁應用安全](/zh-TW/docs/Learn/Server-side/Django/web_application_security) +- [DIY Django 迷你部落格](/zh-TW/docs/Learn/Server-side/Django/django_assessment_blog) diff --git a/files/zh-tw/learn/server-side/django/web_application_security/index.html b/files/zh-tw/learn/server-side/django/web_application_security/index.html deleted file mode 100644 index 7ae8efabcb7dd9..00000000000000 --- a/files/zh-tw/learn/server-side/django/web_application_security/index.html +++ /dev/null @@ -1,180 +0,0 @@ ---- -title: Django web application security -slug: Learn/Server-side/Django/web_application_security -translation_of: Learn/Server-side/Django/web_application_security ---- -
    {{LearnSidebar}}
    - -
    {{PreviousMenuNext("Learn/Server-side/Django/Deployment", "Learn/Server-side/Django/django_assessment_blog", "Learn/Server-side/Django")}}
    - -

    保護用戶數據是任何網站設計的重要部分。我們之前在文章 web 安全中,解釋了一些更常見的安全威脅 -- 本文提供了 Django 的內置保護如何處理這些威脅的實際演示。

    - - - - - - - - - - - - -
    Prerequisites:Read the Server-side progamming "Website security" topic. Complete the Django tutorial topics up to (and including) at least Django Tutorial Part 9: Working with forms.
    Objective:To understand the main things you need to do (or not do) to secure your Django web application.
    - -

    Overview

    - -

    The Website security topic provides an overview of what website security means for server-side design, and some of the more common threats that you may need to protect against. One of the key messages in that article is that almost all attacks are successful when the web application trusts data from the browser.

    - -
    -

    Important: The single most important lesson you can learn about website security is to never trust data from the browser. This includes GET request data in URL parameters, POST data, HTTP headers and cookies, user-uploaded files, etc. Always check and sanitize all incoming data. Always assume the worst.

    -
    - -

    The good news for Django users is that many of the more common threats are handled by the framework! The Security in Django (Django docs) article explains Django's security features and how to secure a Django-powered website.

    - -

    Common threats/protections

    - -

    Rather than duplicate the Django documentation here, in this article we'll demonstrate just a few of the security features in the context of our Django LocalLibrary tutorial.

    - -

    Cross site scripting (XSS)

    - -

    XSS is a term used to describe a class of attacks that allow an attacker to inject client-side scripts through the website into the browsers of other users. This is usually achieved by storing malicious scripts in the database where they can be retrieved and displayed to other users, or by getting users to click a link that will cause the attacker’s JavaScript to be executed by the user’s browser.

    - -

    Django's template system protects you against the majority of XSS attacks by escaping specific characters that are "dangerous" in HTML. We can demonstrate this by attempting to inject some JavaScript into our LocalLibrary website using the Create-author form we set up in Django Tutorial Part 9: Working with forms.

    - -
      -
    1. Start the website using the development server (python3 manage.py runserver).
    2. -
    3. Open the site in your local browser and login to your superuser account.
    4. -
    5. Navigate to the author-creation page (which should be at URL: http://127.0.0.1:8000/catalog/author/create/).
    6. -
    7. Enter names and date details for a new user, and then append the following text to the Last Name field:
      - <script>alert('Test alert');</script>.
      - Author Form XSS test -
      -

      Note: This is a harmless script that, if executed, will display an alert box in your browser. If the alert is displayed when you submit the record then the site is vulnerable to XSS threats.

      -
      -
    8. -
    9. Press Submit to save the record.
    10. -
    11. When you save the author it will be displayed as shown below. Because of the XSS protections the alert() should not be run. Instead the script is displayed as plain text.Author detail view XSS test
    12. -
    - -

    If you view the page HTML source code, you can see that the dangerous characters for the script tags have been turned into their harmless escape code equivalents (e.g. > is now &gt;)

    - -
    <h1>Author: Boon&lt;script&gt;alert(&#39;Test alert&#39;);&lt;/script&gt;, David (Boonie) </h1>
    -
    - -

    Using Django templates protects you against the majority of XSS attacks. However it is possible to turn off this protection, and the protection isn't automatically applied to all tags that wouldn't normally be populated by user input (for example, the help_text in a form field is usually not user-supplied, so Django doesn't escape those values).

    - -

    It is also possible for XSS attacks to originate from other untrusted source of data, such as cookies, Web services or uploaded files (whenever the data is not sufficiently sanitized before including in a page). If you're displaying data from these sources, then you may need to add your own sanitisation code.

    - -

    Cross site request forgery (CSRF) protection

    - -

    CSRF attacks allow a malicious user to execute actions using the credentials of another user without that user’s knowledge or consent. For example consider the case where we have a hacker who wants to create additional authors for our LocalLibrary.

    - -
    -

    Note: Obviously our hacker isn't in this for the money! A more ambitious hacker could use the same approach on other sites to perform much more harmful tasks (e.g. transfer money to their own accounts, etc.)

    -
    - -

    In order to do this, they might create an HTML file like the one below, which contains an author-creation form (like the one we used in the previous section) that is submitted as soon as the file is loaded. They would then send the file to all the Librarians and suggest that they open the file (it contains some harmless information, honest!). If the file is opened by any logged in librarian, then the form would be submitted with their credentials and a new author would be created.

    - -
    <html>
    -<body onload='document.EvilForm.submit()'>
    -
    -<form action="http://127.0.0.1:8000/catalog/author/create/" method="post" name='EvilForm'>
    -  <table>
    -    <tr><th><label for="id_first_name">First name:</label></th><td><input id="id_first_name" maxlength="100" name="first_name" type="text" value="Mad" required /></td></tr>
    -    <tr><th><label for="id_last_name">Last name:</label></th><td><input id="id_last_name" maxlength="100" name="last_name" type="text" value="Man" required /></td></tr>
    -    <tr><th><label for="id_date_of_birth">Date of birth:</label></th><td><input id="id_date_of_birth" name="date_of_birth" type="text" /></td></tr>
    -    <tr><th><label for="id_date_of_death">Died:</label></th><td><input id="id_date_of_death" name="date_of_death" type="text" value="12/10/2016" /></td></tr>
    -  </table>
    -  <input type="submit" value="Submit" />
    -</form>
    -
    -</body>
    -</html>
    -
    - -

    Run the development web server, and log in with your superuser account. Copy the text above into a file and then open it in the browser. You should get a CSRF error, because Django has protection against this kind of thing!

    - -

    The way the protection is enabled is that you include the {% csrf_token %} template tag in your form definition. This token is then rendered in your HTML as shown below, with a value that is specific to the user on the current browser.

    - -
    <input type='hidden' name='csrfmiddlewaretoken' value='0QRWHnYVg776y2l66mcvZqp8alrv4lb8S8lZ4ZJUWGZFA5VHrVfL2mpH29YZ39PW' />
    -
    - -

    Django generates a user/browser specific key and will reject forms that do not contain the field, or that contain an incorrect field value for the user/browser.

    - -

    To use this type of attack the hacker now has to discover and include the CSRF key for the specific target user. They also can't use the "scattergun" approach of sending a malicious file to all librarians and hoping that one of them will open it, since the CSRF key is browser specific.

    - -

    Django's CSRF protection is turned on by default. You should always use the {% csrf_token %} template tag in your forms and use POST for requests that might change or add data to the database.

    - -

    Other protections

    - -

    Django also provides other forms of protection (most of which would be hard or not particularly useful to demonstrate):

    - -
    -
    SQL injection protection
    -
    SQL injection vulnerabilities enable malicious users to execute arbitrary SQL code on a database, allowing data to be accessed, modified, or deleted irrespective of the user's permissions. In almost every case you'll be accessing the database using Django’s querysets/models, so the resulting SQL will be properly escaped by the underlying database driver. If you do need to write raw queries or custom SQL then you'll need to explicitly think about preventing SQL injection.
    -
    Clickjacking protection
    -
    In this attack a malicious user hijacks clicks meant for a visible top level site and routes them to a hidden page beneath. This technique might be used, for example, to display a legitimate bank site but capture the login credentials in an invisible ) represents a nested browsing context, effectively embedding another HTML page into the current page. In HTML 4.01, a document may contain a head and a body or a head and a frameset, but not both a body and a frameset. However, an <iframe> can be used within a normal document body. Each browsing context has its own session history and active document. The browsing context that contains the embedded content is called the parent browsing context. The top-level browsing context (which has no parent) is typically the browser window."><iframe> controlled by the attacker. Django contains clickjacking protection in the form of the X-Frame-Options middleware which, in a supporting browser, can prevent a site from being rendered inside a frame.
    -
    Enforcing SSL/HTTPS
    -
    SSL/HTTPS can be enabled on the web server in order to encrypt all traffic between the site and browser, including authentication credentials that would otherwise be sent in plain text (enabling HTTPS is highly recommended). If HTTPS is enabled then Django provides a number of other protections you can use:
    -
    - - - -
    -
    Host header validation
    -
    Use ALLOWED_HOSTS to only accept requests from trusted hosts.
    -
    - -

    There are many other protections, and caveats to the usage of the above mechanisms. While we hope that this has given you an overview of what Django offers, you should still read the Django security documentation.

    - -
      -
    - -

    Summary

    - -

    Django has effective protections against a number of common threats, including XSS and CSRF attacks. In this article we've demonstrated how those particular threats are handled by Django in our LocalLibrary website. We've also provided a brief overview of some of the other protections.

    - -

    This has been a very brief foray into web security. We strongly recommend that you read Security in Django to gain a deeper understanding.

    - -

    The next and final step in this module about Django is to complete the assessment task.

    - -

    See also

    - - - -

    {{PreviousMenuNext("Learn/Server-side/Django/Deployment", "Learn/Server-side/Django/django_assessment_blog", "Learn/Server-side/Django")}}

    - -

    - -

    In this module

    - - - -

    diff --git a/files/zh-tw/learn/server-side/django/web_application_security/index.md b/files/zh-tw/learn/server-side/django/web_application_security/index.md new file mode 100644 index 00000000000000..2862efd05b1bec --- /dev/null +++ b/files/zh-tw/learn/server-side/django/web_application_security/index.md @@ -0,0 +1,169 @@ +--- +title: Django web application security +slug: Learn/Server-side/Django/web_application_security +translation_of: Learn/Server-side/Django/web_application_security +--- +{{LearnSidebar}}{{PreviousMenuNext("Learn/Server-side/Django/Deployment", "Learn/Server-side/Django/django_assessment_blog", "Learn/Server-side/Django")}} + +保護用戶數據是任何網站設計的重要部分。我們之前在文章 web 安全中,解釋了一些更常見的安全威脅 -- 本文提供了 Django 的內置保護如何處理這些威脅的實際演示。 + + + + + + + + + + + + +
    Prerequisites: + Read the Server-side progamming "Website security" topic. Complete the Django tutorial topics up to (and including) at + least + Django Tutorial Part 9: Working with forms. +
    Objective: + To understand the main things you need to do (or not do) to secure your + Django web application. +
    + +## Overview + +The [Website security](/en-US/docs/Web/Security) topic provides an overview of what website security means for server-side design, and some of the more common threats that you may need to protect against. One of the key messages in that article is that almost all attacks are successful when the web application trusts data from the browser. + +> **警告:** The single most important lesson you can learn about website security is to **never trust data from the browser**. This includes `GET` request data in URL parameters, `POST` data, HTTP headers and cookies, user-uploaded files, etc. Always check and sanitize all incoming data. Always assume the worst. + +The good news for Django users is that many of the more common threats are handled by the framework! The [Security in Django](https://docs.djangoproject.com/en/2.0/topics/security/) (Django docs) article explains Django's security features and how to secure a Django-powered website. + +## Common threats/protections + +Rather than duplicate the Django documentation here, in this article we'll demonstrate just a few of the security features in the context of our Django [LocalLibrary](/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website) tutorial. + +### Cross site scripting (XSS) + +XSS is a term used to describe a class of attacks that allow an attacker to inject client-side scripts _through_ the website into the browsers of other users. This is usually achieved by storing malicious scripts in the database where they can be retrieved and displayed to other users, or by getting users to click a link that will cause the attacker’s JavaScript to be executed by the user’s browser. + +Django's template system protects you against the majority of XSS attacks by [escaping specific characters](https://docs.djangoproject.com/en/2.0/ref/templates/language/#automatic-html-escaping) that are "dangerous" in HTML. We can demonstrate this by attempting to inject some JavaScript into our LocalLibrary website using the Create-author form we set up in [Django Tutorial Part 9: Working with forms](/en-US/docs/Learn/Server-side/Django/Forms). + +1. Start the website using the development server (`python3 manage.py runserver`). +2. Open the site in your local browser and login to your superuser account. +3. Navigate to the author-creation page (which should be at URL: [`http://127.0.0.1:8000/catalog/author/create/`](http://127.0.0.1:8000/catalog/author/create/)). +4. Enter names and date details for a new user, and then append the following text to the Last Name field: + ``. + ![Author Form XSS test](author_create_form_alert_xss.png) + + > **備註:** This is a harmless script that, if executed, will display an alert box in your browser. If the alert is displayed when you submit the record then the site is vulnerable to XSS threats. + +5. Press **Submit** to save the record. +6. When you save the author it will be displayed as shown below. Because of the XSS protections the `alert()` should not be run. Instead the script is displayed as plain text.![Author detail view XSS test](author_detail_alert_xss.png) + +If you view the page HTML source code, you can see that the dangerous characters for the script tags have been turned into their harmless escape code equivalents (e.g. `>` is now `>`) + +```html +

    Author: Boon<script>alert('Test alert');</script>, David (Boonie)

    +``` + +Using Django templates protects you against the majority of XSS attacks. However it is possible to turn off this protection, and the protection isn't automatically applied to all tags that wouldn't normally be populated by user input (for example, the `help_text` in a form field is usually not user-supplied, so Django doesn't escape those values). + +It is also possible for XSS attacks to originate from other untrusted source of data, such as cookies, Web services or uploaded files (whenever the data is not sufficiently sanitized before including in a page). If you're displaying data from these sources, then you may need to add your own sanitisation code. + +### Cross site request forgery (CSRF) protection + +CSRF attacks allow a malicious user to execute actions using the credentials of another user without that user’s knowledge or consent. For example consider the case where we have a hacker who wants to create additional authors for our LocalLibrary. + +> **備註:** Obviously our hacker isn't in this for the money! A more ambitious hacker could use the same approach on other sites to perform much more harmful tasks (e.g. transfer money to their own accounts, etc.) + +In order to do this, they might create an HTML file like the one below, which contains an author-creation form (like the one we used in the previous section) that is submitted as soon as the file is loaded. They would then send the file to all the Librarians and suggest that they open the file (it contains some harmless information, honest!). If the file is opened by any logged in librarian, then the form would be submitted with their credentials and a new author would be created. + +```html + + + +
    + + + + + +
    + +
    + + + +``` + +Run the development web server, and log in with your superuser account. Copy the text above into a file and then open it in the browser. You should get a CSRF error, because Django has protection against this kind of thing! + +The way the protection is enabled is that you include the `{% csrf_token %}` template tag in your form definition. This token is then rendered in your HTML as shown below, with a value that is specific to the user on the current browser. + +```html + +``` + +Django generates a user/browser specific key and will reject forms that do not contain the field, or that contain an incorrect field value for the user/browser. + +To use this type of attack the hacker now has to discover and include the CSRF key for the specific target user. They also can't use the "scattergun" approach of sending a malicious file to all librarians and hoping that one of them will open it, since the CSRF key is browser specific. + +Django's CSRF protection is turned on by default. You should always use the `{% csrf_token %}` template tag in your forms and use `POST` for requests that might change or add data to the database. + +### Other protections + +Django also provides other forms of protection (most of which would be hard or not particularly useful to demonstrate): + +- SQL injection protection + - : SQL injection vulnerabilities enable malicious users to execute arbitrary SQL code on a database, allowing data to be accessed, modified, or deleted irrespective of the user's permissions. In almost every case you'll be accessing the database using Django’s querysets/models, so the resulting SQL will be properly escaped by the underlying database driver. If you do need to write raw queries or custom SQL then you'll need to explicitly think about preventing SQL injection. +- Clickjacking protection + - : In this attack a malicious user hijacks clicks meant for a visible top level site and routes them to a hidden page beneath. This technique might be used, for example, to display a legitimate bank site but capture the login credentials in an invisible [) represents a nested browsing context, effectively embedding another HTML page into the current page. In HTML 4.01, a document may contain a head and a body or a head and a frameset, but not both a body and a frameset. However, an \