在/ polls /上的TemplateDoesNotExist

时间:2014-05-15 16:23:57

标签: python django django-templates django-views

我一直在尝试Django教程Django Tutorial Page 3并遇到此错误

  

" TemplateDoesNotExist at / polls /"

我认为问题在于我的代码指向模板文件index.html。这是index.htmlmysite/polls/templates/polls的文件结构。 我正在复制settings.pyviews.py

settings.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`

如果我错过任何可以提供更清晰画面的信息,请告诉我。提前谢谢。

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/'

10 个答案:

答案 0 :(得分:5)

尝试将模板文件夹放在项目根文件夹中:

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.html中存储的模板一起使用,请尝试这样:

转到mysite并运行

python manage.py shell

mysite作为上下文运行交互式解释器。然后运行:

from settings import TEMPLATE_DIRS
print TEMPLATE_DIRS

它会输出类似

的内容
('/var/www/mithril/templates/', '/home/dmitry/proj/mithril/templates/')

Django使用此目录查找模板。 因此,您应将目录polls/放在TEMPLATE_DIRS的文件夹中。

答案 1 :(得分:3)

哇哇哇哇哇我们不提倡不再重复使用应用程序。

对于不适合其他地方的模板(通常是您的基本模板,可能是某些部分模板,如表单等),可以将它们放在根模板目录中(即/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,并包含基础urls.py中的网址。当然,以新的项目需要的任何方式修改应用程序。

这也意味着如果您使用带侧边栏导航的编辑器(其中大部分是现在),您不必一直向下滚动到模板以查找该应用的模板。当你开始处理大型项目时,这会变得乏味,快速。

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

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

回答你实际问过的问题:

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

在相关的说明中,您可能不应该在Python目录中拥有项目。

答案 2 :(得分:2)

我遇到了同样的问题,并且发现index中还有一个名为site-packages的HTML文件。因此,我只是将当前的HTML文件更改为index1,它可以正常工作。

答案 3 :(得分:1)

您遵循此结构,

mysite/
   mysite/
      templates/
         polls/
           index.html

有一些东西怀疑你的TEMPLATE_DIRS路径。它应该指向模板目录的根目录。

import os

PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))

...


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

在您的错误日志django中搜索这些路径,

C:\Python34\mysite\templates\polls\index.html 
C:\Python34\mysite\polls\templates\polls\index.html 

答案 4 :(得分:1)

您忘记在settings.py

中的INSTALLED_APP中添加您的应用配置

INSTALLED_APPS =(

'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

  

startapp 命令可创建 apps.py 文件。因为它不使用 default_app_config (a   气馁的API),你必须指定app config的路径,例如'polls.apps.PollsConfig',in    INSTALLED_APPS 供其使用(而非'民意调查')。

答案 5 :(得分:1)

在您的settings.py文件中,添加此

TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')

然后在TEMPLATES DIRS中添加此内容,

TEMPLATES = [
{
    ...
    'DIRS': [TEMPLATE_DIR,],
    ...
},]

答案 6 :(得分:1)

尝试替换:

template = loader.get_template('polls/index.html')

与此:

template = loader.get_template('index.html')

答案 7 :(得分:0)

检查您是否忘记了&#39;在

  

/轮询/模板

它的

  

&#39; /轮询/模板&#39;文件夹中。

答案 8 :(得分:0)

确保您没有将detail.html拼写为details.html。这是我的问题。

答案 9 :(得分:0)

问题出在您的文件夹结构上。由于您位于df[['a','b','c','d']].iplot(secondary_y=['c', 'd'])文件夹中,因此应使用此polls而不是template = loader.get_template('index.html')

这是因为python路径如何工作,请参见此处OS Path