3.Django動態頁面
上一章節我們實現的helloworld視圖是用來演示Django網頁是創建的,它不是一個動態網頁,每次運行/helloworld/,我們都將看到相同的內容,它類似一個靜態HTML文件。
接下來我們將實現另一個視圖,加入動態內容,例如當前日期和時間顯示在網頁上。通過簡單的下一步,來演示Django的這個技術。
3.1.一個簡單的動態頁面例子
這個視圖做兩件事情: 獲取服務器當前日期和時間,並返回包含這些值的HttpResponse 。為了讓Django視圖顯示當前日期和時間,在代碼中引入datetime模塊,然后要把語句:datetime.datetime.now()放入視圖函數,然后返回一個HttpResponse對象即可。代碼如下:
from django.http import HttpResponse import datetime def helloworld(request): return HttpResponse("Hello world") def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)
函數的第二行代碼用 Python 的格式化字符串(format-string)功能構造了一段 HTML 響應。 字符串中的%s是占位符,字符串后面的百分號表示用它后面的變量now的值來代替%s。變量%s是一個datetime.datetime對象。它雖然不是一個字符串,但是%s(格式化字符串)會把它轉換成字符串,如:2014-11-03 14:15:43.465000。這將導致HTML的輸出字符串為:It is now 2014-11-03 14:15:43.465000。
完成添加views.py上述代碼之后,同上,在urls.py中添加URL模式,以告訴Django由哪一個URL來處理這個視圖。 如下:我們定義/mytime/URL:
from django.conf.urls import patterns, include, url from mysite.views import hello,current_datetime # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'mysite.views.home', name='home'), # url(r'^mysite/', include('mysite.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), ('^helloworld/$', hello), ('^mytime/$', current_datetime), )
寫好視圖並且更新URLconf之后,運行命令python manage.py runserver運行服務器,在瀏覽器中輸入http://127.0.0.1:8000, 我們將看到增加的mytime頁面目錄。
在瀏覽器中輸入http://127.0.0.1:8000/mytime/。 網頁將顯示當前的日期和時間。
3.2. 小結
本小節通過一個簡單例子展示了動態頁面的例子,目前為止HTML源碼被直接硬編碼在 Python 代碼之中,下一章節我們將介紹Django模板系統,如何解決Python代碼與頁面設計分離的問題。