在学习Django教程时遇到了一个我无法解决的问题。希望你能帮忙。我错过了什么?运行本教程几次,现在双重检查所有工作,代码似乎匹配。
错误:“Not Found:/polls/index.html”
mysite/urls.py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^polls/', include('polls.urls')),
]
字符串
polls/templates/polls/index.html:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
型
民意调查/urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
型
民意调查/views.py:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
型
2条答案
按热度按时间4urapxun1#
x1c 0d1x的数据
从docs
模板命名空间
现在,我们可能可以把模板直接放在polls/templates中(而不是创建另一个polls子目录),但这实际上是一个坏主意。Django会选择它找到的第一个名称匹配的模板,如果你在不同的应用程序中有一个同名的模板,Django将无法区分它们。我们需要能够将Django指向正确的位置,而确保这一点的最简单方法是将它们命名空间。也就是说,通过将这些模板放在另一个为应用程序本身命名的目录中。
在setting.py中,替换为以下部分:
字符串
hs1rzwqc2#
只需在settings.py添加投票。应用程序
字符串
现在,您可以在
polls/templates/polls/index.html
添加模板,并通过loader.get_template('polls/index.html')
或型