python - TemplateDoesNotExist 位于/polls/

标签 python django django-templates django-views

我一直在试用 Django 教程 Django Tutorial Page 3并遇到了这个错误

"TemplateDoesNotExist at /polls/ " .

我假设问题出在我的代码指向模板文件 index.html。这是我的 index.html 文件结构:mysite/polls/templates/polls。 我正在将我的 settings.pyviews.py 复制到这里。

设置.py

TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

观点。 Py

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)

有人可以调查一下并帮助我解决这个错误。任何帮助,将不胜感激。 这是回溯`环境:

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`

如果我遗漏了任何可以提供更清晰图片的内容,请告诉我。提前致谢。

设置.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/'

最佳答案

哇哇哇。我们不要提倡应用程序的不可重用性。

对于不适合其他任何地方的模板(通常是您的基本模板,可能是一些部分模板,如表单包含等),将它们放在您的根模板目录(即 /path/to/project/templates/base.html)。您可以在 View 中引用它们以呈现为 base.html

对于其他模板,我建议您将它们放在包含呈现给这些模板的 View 的应用程序目录中。例如,您的民意调查索引将位于诸如 /path/to/project/polls/templates/polls/index.html 之类的地方。

额外的 polls 目录可能看起来多余,但原因是 django 模板加载器将(逻辑上)将所有模板转储到一个目录中。因此,我们使用第二个 polls 目录来区分可能存在的多个 index.html 模板。所以在您看来,您应该照常使用 polls/index.html

之所以说这是一件好事,是因为它使您的应用程序更容易重用。写了一个民意测验应用程序?你已经把它们都写好了。如果你这样做,并且还在你的应用程序的静态目录中保留你的应用程序特定的静态文件(js、css、图像等),并且每个应用程序都有一个 urls.py,通常你会将您的应用程序从一个项目移动到另一个项目需要做的是复制目录,添加到新项目的 INSTALLED_APPS,并包含来自您的基础 urls.py 的 url。当然,您可以根据新项目的需要以任何方式修改应用程序。

这也意味着,如果您使用的是带侧边栏导航的编辑器(现在大多数都是这样),您无需一直向下滚动到模板即可找到该应用的模板。当您开始处理大型项目时,这会变得乏味、快速。

使用此技术时唯一要记住的是,您的 TEMPLATE_LOADERS 设置中必须有 django.template.loaders.app_directories.Loader。这是默认设置,因此您通常不必担心。

django 文档中有一个很好的指南:https://docs.djangoproject.com/en/1.7/intro/reusable-apps/

回答你实际提出的问题:

您的 index.html 应该在此处:C:\Python34\mysite\polls\templates\polls\index.html。如果不是,那就是你做错了。

在相关说明中,您可能不应该将项目放在 Python 目录中。

关于python - TemplateDoesNotExist 位于/polls/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23683787/

相关文章:

python 3.4 将文本文件过滤到列表中

django - 如何从覆盖范围中排除文件?

django - 如何在 Django 模板中进行 1 次迭代后中断 "for loop"

css - block 内容中的文本溢出

python - 使用键中的冒号解析 JSON

python - 获取 : 'TypeError: can only concatenate tuple (not "int") to tuple', 即使它是一个 int

python - 如何在不考虑 div 索引的情况下识别 XPath?

python - KeyboardInterrupt 在 ipython 下的 Python 2.7 中不可预测,我怎样才能让它 *always* 中止当前评估?

python - 如何修改数据库中已经迁移的模型?

Django、mod_wsgi、psycopg2 配置不当 : Error loading psycopg2 module: No module named _psycopg