/polls/处的模板不存在

6 投票
12 回答
12921 浏览
提问于 2025-04-18 06:41

我在尝试Django的教程Django教程第3页时遇到了一个错误。

错误信息是:“在 /polls/ 找不到模板。”

我猜问题出在我的代码没有正确指向模板文件index.html。我的index.html文件结构是:mysite/polls/templates/polls。下面是我的settings.pyviews.py的内容。

settings.py

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

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

12 个回答

3

我也遇到了同样的问题,后来我发现site-packages文件夹里有另一个叫index的HTML文件。于是我把我现在的HTML文件改成了index1,结果就好了。

4

你忘了在settings.py文件里的INSTALLED_APPS中添加你的应用配置。

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(这是不推荐使用的接口),所以你必须在INSTALLED_APPS中指定应用配置的路径,比如'polls.apps.PollsConfig',这样它才能被使用(而不是仅仅用'polls')。

5

试着把下面的内容替换成:

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

用这个:

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

哎呀,等等。我们可不能提倡不让应用程序可重用。

对于那些不适合放在其他地方的模板(通常是你的基础模板,或者一些部分模板,比如表单包含等),把它们放在你的根模板目录里是可以的(比如 /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 中包含这些 urls,就可以把应用从一个项目迁移到另一个项目。当然,你还需要根据新项目的需求对应用进行修改。

这还意味着,如果你使用的是带有侧边导航的编辑器(现在大多数编辑器都是这样的),你就不需要一直滚动到模板的底部去找那个应用的模板。当你开始处理大型项目时,这会变得非常繁琐。

使用这个技巧时唯一需要记住的是,你必须在 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 目录里。

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 指定的文件夹里。

撰写回答