rv_*_*v_k 3 python django django-templates django-views
我一直在尝试Django教程Django Tutorial第3页并遇到了这个错误
"在/ polls /上的TemplateDoesNotExist".
我假设问题是我的代码指向模板文件index.html.这是我的文件结构index.html: mysite/polls/templates/polls.我正在复制我settings.py和views.py这里.
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
Run Code Online (Sandbox Code Playgroud)
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
from polls.models import Poll
# Create your views here.
#def index(request):
#return HttpResponse("Hello, world. You are at the poll index.")
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = RequestContext(request, {
'latest_poll_list': latest_poll_list,
})
return HttpResponse(template.render(context))
def detail(request,poll_id):
return HttpResponse("You're looking at the results of the poll %s." % poll_id)
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request,poll_id):
return HttpResponse("You're voting on poll %s." % poll_id)
Run Code Online (Sandbox Code Playgroud)
有人可以调查它并帮助我解决这个错误.任何帮助,将不胜感激.这是追溯`环境:
Request Method: GET
Request URL: http://localhost:8000/polls/
Django Version: 1.6.4
Python Version: 3.4.0
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
C:\Python34\mysite\templates\polls\index.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
C:\Python34\lib\site-packages\django\contrib\admin\templates\polls\index.html (File does not exist)
C:\Python34\lib\site-packages\django\contrib\auth\templates\polls\index.html (File does not exist)
C:\Python34\mysite\polls\templates\polls\index.html (File does not exist)
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\mysite\polls\views.py" in index
14. template = loader.get_template('polls/index.html')
File "C:\Python34\lib\site-packages\django\template\loader.py" in get_template
138. template, origin = find_template(template_name)
File "C:\Python34\lib\site-packages\django\template\loader.py" in find_template
131. raise TemplateDoesNotExist(name)
Exception Type: TemplateDoesNotExist at /polls/
Exception Value: polls/index.html`
Run Code Online (Sandbox Code Playgroud)
如果我错过任何可以提供更清晰画面的信息,请告诉我.提前致谢.
Settings.py"""
Django settings for mysite project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ma_x5+pnvp$o7#5g#lb)0g$sa5ln%k(z#wcahwib4dngbbe9^='
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'C://Python34/mysite/db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
#TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
Run Code Online (Sandbox Code Playgroud)
尝试将模板文件夹放在项目根文件夹中:
mysite/templates/polls/index.html
说明
你的模板目录是
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
它只包含一个目录: /path/to/your/project/templates
你的index.html位于 /path/to/your/project/polls/templates
更新
正如你所说它不适用于存储在mysite/templates/polls/index.htmllet中的模板尝试这种方式:
去mysite跑
python manage.py shell
Run Code Online (Sandbox Code Playgroud)
使用mysiteas context 运行交互式解释器.然后运行:
from settings import TEMPLATE_DIRS
print TEMPLATE_DIRS
Run Code Online (Sandbox Code Playgroud)
它会输出类似的东西
('/var/www/mithril/templates/', '/home/dmitry/proj/mithril/templates/')
Run Code Online (Sandbox Code Playgroud)
Django使用此目录来查找模板.因此,您应该将目录polls/放在文件夹中TEMPLATE_DIRS.
哇,哇。让我们不要提倡应用不可重用。
对于不适合其他任何地方的模板(通常是您的基本模板,也许有些局部模板,例如表单包含等),可以将它们放在根模板目录中(即/path/to/project/templates/base.html)。您将在视图中引用它们以将其呈现为base.html。
对于其他模板,我建议您将它们放在包含渲染到这些模板的视图的应用程序目录中。例如,您的民意测验索引将位于/path/to/project/polls/templates/polls/index.html。
多余的polls目录可能看起来很多余,但是原因是django模板加载器会(逻辑上)将所有模板转储到一个目录中。因此,我们使用第二个polls目录来区分index.html可能存在的多个模板。因此,在您看来,您将polls/index.html照常使用。
之所以如此,是因为它使您的应用程序更易于重用。编写了一个民意调查应用程序?您都写了。如果执行此操作,并且还将应用程序特定的静态文件(js,css,图像等)保留在应用程序的静态目录中,并且urls.py为每个应用程序都有一个,通常您需要做的所有事情才能将应用程序从一个项目中移出另一个是复制目录,添加到新项目的目录INSTALLED_APPS,并包括base中的url urls.py。当然,您可以根据需要为新项目修改应用程序。
这也意味着,如果您使用的是带有侧边栏导航的编辑器(如今,大多数情况下都是这样),则无需一直向下滚动到模板即可找到该应用程序的模板。当您开始进行大型项目时,这会变得很繁琐,快速。
使用此技术时要记住的唯一事情是您必须具有django.template.loaders.app_directories.Loader自己的TEMPLATE_LOADERS设置。这是默认设置,因此您通常不必担心。
django文档中对此有一个很好的指导:https : //docs.djangoproject.com/en/1.7/intro/reusable-apps/
要回答您实际提出的问题:
您index.html应该在这里:C:\Python34\mysite\polls\templates\polls\index.html。如果不是,那就是您做错了。
与此相关的是,您可能不应该将项目放在Python目录中。
小智 5
尝试更换:
template = loader.get_template('polls/index.html')
Run Code Online (Sandbox Code Playgroud)
有了这个:
template = loader.get_template('index.html')
Run Code Online (Sandbox Code Playgroud)