2012-05-31 66 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重定向。 –