1. 程式人生 > >django學習系列之檢視篇

django學習系列之檢視篇

前面寫了資料庫,或者說模型和模板,MTV裡面就差V了,也就是檢視。

所謂的檢視,只不過是一個接受Web請求並返回Web響應的python函式。而這個響應不僅僅是html內容,還可以是一次重定向、一條404錯誤、一張圖片,或其它任何東西。

開啟views.py檔案,新增程式碼:

from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>Itis now %s.</body></html>" % now
    return HttpResponse(html)

挑重點分析一下,檢視就是current_datetime()函式。這個檢視返回一個HttpResponse物件。

這個檢視怎麼被找到呢?也就是說,怎麼將一個URLhttp://mysite.com/time/ 對映到試圖呢django使用URLconf

開啟urls.py檔案,

1.引入current_datetime檢視,假如這個檢視寫在mysite.views模組中,就新增以下程式碼:

from mysite.views importcurrent_datetime

2.找到urlpatterns= patterns('',

)

在裡面新增一項:(r'^time/$',current_datetime),

這樣遇到URL/time/的請求,都會到mysite.views模組中找到current_datetime試圖來處理。

今天先講最基本的檢視,後面還有檢視的高階應用。