2013-06-25 77 views
0

我正在創建一個顯示當前日期和時間偏移一定小時數的視圖。我們的目標是設計一個網站的頁面/時間/加號/ 1 /在一個小時內顯示日期和時間,頁面/時間/加號/ 2 /在兩個小時內顯示日期和時間,頁面/時間/加號/ 3 /在三個小時內顯示日期和時間,依此類推。這是我在views.py功能:Django中的動態網址

def hours_ahead(request, offset): 
    try: 
     offset = int(offset) 
    except ValueError: 
     raise Http404() 
    dt = datetime.datetime.now() + datetime.timedelta(hours=offset) 
    html = "In %s hour(s), it will be %s." % (offset, dt) 
    return HttpResponse(html) 

,這是我url.py文件的內容:

from django.conf.urls import patterns, include, url 
from aplicacion1.views import hours_ahead 

urlpatterns = patterns('', 
    url(r'^time/plus/(d{1,2})/$', hours_ahead),) 

在views.py這個模式應該只接受數字一個或兩個數字否則,Django應該顯示錯誤「未找到頁面」。網址http://127.0.0.1:8000/time/plus/(no hours)也應該引發404錯誤。但是,當我運行的服務器,並嘗試訪問一個網址像http://127.0.0.1:8000/time/plus/24/,告訴我下面的錯誤:

Page not found (404) 
Request Method: GET 
Request URL:  

http://127.0.0.1:8000/time/plus/24/ 
Using the URLconf defined in cibernat.urls, Django tried these URL patterns, in this order: 
^$ 
^time/$ 
^time/plus\d+/$ 
^admin/doc/ 
^admin/ 
The current URL, time/plus/24/, didn't match any of these. 

什麼是錯誤,我在做什麼?我看到的是,正則表達式看起來是正確的

回答

3

你的URL模式應該是

url(r'^time/plus/(\d{1,2})/$', hours_ahead), 

d

之前忘了 \