Django 找不到我的模板
我在Windows XP SP3上运行Python 2.6.1和Django 1.2.1。我使用JetBrains的PyCharm 1.0来创建和部署我的Django应用。
我对Python还比较陌生,现在正在通过网站上的“写你的第一个Django应用”来学习Django,具体是投票应用。我在第三部分遇到了困难。
当我添加“写你的第一个视图”的简单回调函数时,一切都很顺利。
但是当我到“写一些实际有用的视图”时,我就卡住了。
我按照说明修改了index视图:
- 在views.py中添加一个新方法(注意 - 模板已经准备好,来自'polls/index.html'):
- 将index.html模板添加到
site-templates/polls/
文件夹中 - 修改settings.py,让它指向
site-templates
文件夹
这是我在views.py中的代码:
from django.template import Context, loader
from polls.models import Poll
from django.http import HttpResponse
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
t = loader.get_template('polls/index.html')
c = Context({
'latest_poll_list': latest_poll_list,
})
return HttpResponse(t.render(c))
这是我在settings.py中的一行:
TEMPLATE_DIRS = ('/site-templates/')
但是当我运行时,仍然收到这个消息:
TemplateDoesNotExist at /polls/
polls/index.html
Request Method: GET
Request URL: http://localhost:8000/polls/
Django Version: 1.2.1
Exception Type: TemplateDoesNotExist
Exception Value:
polls/index.html
异常是在loader.py中抛出的。我的调试设置看起来是这样的:
TEMPLATE_CONTEXT_PROCESSORS
('django.core.context_processors.auth', 'django.core.context_processors.request')
TEMPLATE_DEBUG
True
TEMPLATE_DIRS
('/site-templates',)
TEMPLATE_LOADERS
('django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader')
我的目录结构是这样的:
我漏掉了什么吗?settings.py有问题吗?请给我一些建议。
6 个回答
6
Django有一些固定的模式和理念。尽量使用相同的配置,否则你就得改变Django的核心模式。
Django中模板的模式是这样的:
polls/templates/polls/index.html
但是要使用它,你需要在配置中添加已安装的应用:
INSTALLED_APPS = [
'polls.apps.PollsConfig', #<-- Here this shoud be solve it
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',]
想了解更多信息,可以查看:
https://docs.djangoproject.com/en/3.0/intro/tutorial02/#activating-models
42
我也遇到过同样的问题。在我的情况下,错误的原因是我的'app'没有在项目的settings.py文件中的INSTALLED_APPS
列表里。
这个错误会提示你类似的错误信息。
line 25, in get_template TemplateDoesNotExist(template_name, chain=chain)
django.template.exceptions.TemplateDoesNotExist: authControll/index.html
settings.py --> 应用程序定义
INSTALLED_APPS = [
...,
'authControll'
]
13
在
一个方便的做法是在你的设置文件顶部插入:
import os
DIRNAME = os.path.abspath(os.path.dirname(__file__))
然后在你使用路径的地方,使用os.path.join
。举个例子,你的
TEMPLATE_DIRS = (
os.path.join(DIRNAME, 'site-templates/'),
)