投票站的临时选民/

2024-03-28 14:00:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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

"TemplateDoesNotExist at /polls/ " .

我假设问题是我的代码指向模板文件index.html。这是我的文件结构index.htmlmysite/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/'

Tags: djangopyindexsettingsoshtmltemplatecontrib
3条回答

我遇到了同样的问题,我注意到在site-packages中还有一个名为index的HTML文件。所以我把当前的HTML文件改成了index1,它就工作了。

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

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中的模板,让我们这样尝试:

去我的网站跑

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的文件夹中。

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

对于其他地方不适合的模板(通常是基本模板,可能是一些部分模板,如form includes等),可以将它们放在根模板目录中(即/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的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目录中。

相关问题 更多 >