0

我被困在实际做某事的写视图部分。我已按照指示将我的观点修改为以下内容:

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.
)

但是,在 localhost ( ) 中运行服务器后,我仍然在浏览器中看到以下错误消息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.

我的代码或文件有问题,但无法弄清楚到底是什么。

4

1 回答 1

3

索引视图的 url 是/polls/,不是/polls/index.html

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

如果你想让 /polls/index.html 工作,你必须为其添加一个 url 模式,例如:

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

However, you probably don't want to do that. One of the nice things about Django is that you can define the urls independently of the views and templates, so you don't need 'crufty' urls that end in .html.

于 2012-05-31T02:01:16.253 回答