2012-05-31 65 views
0

我被卡在Write views that actually do something部分。 我修改我的意見是以下的指示:django中的模板問題

from django.template import Context, loader 
from polls.models import Poll 
from django.http import HttpResponse 

def index(request): 
    latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] 
    t = loader.get_template('polls/index.html') 
    c = Context({ 
     'latest_poll_list': latest_poll_list, 
    }) 
    return HttpResponse(t.render(c)) 

def detail(request, poll_id): 
    return HttpResponse("You're looking at poll %s." % poll_id) 

def results(request, poll_id): 
    return HttpResponse("You're looking at the results of the poll %s." % poll_id) 

def vote(request, poll_id): 
    return HttpResponse("You're voting on poll %s." % poll_id) 

我做了我的模板目錄是/home/stanley/mytemplates/polls/作爲教程指導,這是相關的線,在settings.py匹配:

TEMPLATE_DIRS = (
    "/home/stanley/mytemplates/", 
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". 
    # Always use forward slashes, even on Windows. 
    # Don't forget to use absolute paths, not relative paths. 
) 

不過,我仍然在我的瀏覽器中看到以下錯誤消息,在本地主機(http://127.0.0.1:8000/polls/index.html)上運行的服務器後:

Page not found (404) 
Request Method: GET 
Request URL: http://localhost:8000/polls/index.html 
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: 
^polls/$ 
^polls/(?P<poll_id>\d+)/$ 
^polls/(?P<poll_id>\d+)/results/$ 
^polls/(?P<poll_id>\d+)/vote/$ 
^admin/ 
^admin/ 
The current URL, polls/index.html, didn't match any of these. 
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. 

我正在做我的代碼或文件有問題,但不能完全弄清楚究竟是什麼。有任何想法嗎?

在此先感謝您的建議!

+3

如果您嘗試訪問'http://127.0.0.1:8000/polls /'(離開index.html),會發生什麼? – jozzas

回答

3

索引視圖的網址是/polls/,而不是/polls/index.html

url(r'^polls/$', 'polls.views.index'), 

如果你想/polls/index.html工作,你必須添加一個URL模式爲它,例如:

url(r'^/polls/index.html', 'polls.views.index'), 

然而,你可能不希望這樣做。關於Django的好處之一是你可以獨立於視圖和模板來定義url,所以你不需要在`.html'結尾的'crufty'url。

+0

確實。幾年前,我有一位客戶*堅持認爲*所有內容都必須以title-slug爲基礎,並以'.html'結尾。要管理巨大的PITA,尤其是當他們開始更改/更正標題時,我們必須跟蹤所有301重定向。 –