14
The Django Book Chapter 2 Views and URLconfs 20160524 Django讀書會-EK

Chapter 2 views and urlconfs

Embed Size (px)

Citation preview

Page 1: Chapter 2 views and urlconfs

The Django Book Chapter 2 Views and URLconfs

20160524Django讀書會-EK

Page 2: Chapter 2 views and urlconfs

內容

2.1 Your First View

2.2 Your First URLconf

2.3 Regular Expressions

2.4 How Django Process a Request

2.5 Your Second View Dynamic Content

2.6 Your Third View Dynamic URL

2

Page 3: Chapter 2 views and urlconfs

新增 mysite/views.py

2.1 Your First View

class in django.http module

慣例上,最少要一個變數 request

1. 匯入 HttpResponse2. 寫一個 view 的函數3. 最後 回傳結果,透過HttpRespnse傳文字 Hello world

3

Page 4: Chapter 2 views and urlconfs

2.2 First URLconf寫完 view hello後,Django仍然不認識它,要透過URLconf,讓URLs和view函數可

以對應

1. 把寫好的 hello (view) import 進來 2. 將對應 hello函數 的路徑寫出來

r’^hello/$’

r:raw string^:start$:end

4

Page 5: Chapter 2 views and urlconfs

2.2 First URLconf● 如果 pattern ‘^hello/’(沒有$)

○ 它會去尋找任何一個開頭是 /hello/,像是 /hello/foo or /hello/bar

● 如果 pattern ‘hello/$’(沒有^)○ 它會去尋找任何一個結尾是 /hello/,像是 /foo/bar/hello

● 如果 pattern ‘hello/’(沒有$,^)○ 它會去尋找任何一個包含 /hello/,像是 /foo/hello/bar

因此一開頭結尾一定要加上^和$

5

Page 6: Chapter 2 views and urlconfs

2.3 Regular Expressions為一種正規表示法

6

Page 7: Chapter 2 views and urlconfs

2.4 How Django Processes a Request(1/2)1.當輸入網址 127.0.0.1:8000/hello

2.會根據 settings.py ROOT_URLCONF= ‘xxx.urls’

3. 對應到 hello,到 views.py裡面去執行

7

Page 8: Chapter 2 views and urlconfs

2.4 How Django Processes a Request(2/2)4.找到 def hello

5.執行 return,透過 HttpResponse 回傳字串 “Hello world”,並顯示在瀏覽器上

8

Page 9: Chapter 2 views and urlconfs

2.5 Second View: Dynamic Content(1/3)接下來動態的內容要顯示進入網頁的日期和時間,會用到datetime

1.先在views.py實作出來。

9

Page 10: Chapter 2 views and urlconfs

2.5 Second View: Dynamic Content(2/3)2.在urls.py設定,讓網址可以對應到實作

10

Page 11: Chapter 2 views and urlconfs

2.5 Second View: Dynamic Content(3/3)3.進入 127.0.0.1:8000/time

11

Page 12: Chapter 2 views and urlconfs

2.6 Third View: Dynamic URLs(1/3)上一個動態內容出現在在時間,接下來要透過動態的方式透過網址傳值來更改顯示

內容。

希望做到 127.0.0.1:8000/time/plus/** 可以讓顯示的時間 往後增加0-99小時

1.改寫urls.py

d:10進位數字{1,2}:1-2位數字\d{1,2}:可以任意 0-99的數字

12

Page 13: Chapter 2 views and urlconfs

2.6 Third View: Dynamic URLs(2/3)2.實作 hours_ahead (增加**小時)

將 offset轉成數字,如果ValueError出現404錯誤

dt:將現在時間加上 offset時間datetime.timedelta(hours):轉成 hour的格式

13

Page 14: Chapter 2 views and urlconfs

2.6 Third View: Dynamic URLs(3/3)3.瀏覽器顯示

14