Django无法找到我的模板

duf*_*ymo 6 python django django-templates django-views

我在Windows XP SP3上运行Python 2.6.1和Django 1.2.1.我正在使用JetBrains PyCharm 1.0来创建和部署我的Django应用程序.

我对Python相对缺乏经验,我开始通过跟随网站上的"编写你的第一个Django应用程序" - 民意调查应用程序来学习Django.我被困在第3部分.

当我为"编写你的第一个视图"添加简单的回调函数时,一切都很好.

当我开始写"实际做某事的观点"时,我遇到了障碍.

我按照说明修改了索引视图:

  1. 向views.py添加一个新方法(注意 - 模板已从'polls/index.html'准备好):
  2. 将index.html模板添加到site-templates/polls/文件夹
  3. 修改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))
Run Code Online (Sandbox Code Playgroud)

这是我的settings.py中的行:

TEMPLATE_DIRS = ('/site-templates/')
Run Code Online (Sandbox Code Playgroud)

但是我跑的时候仍然收到这条消息:

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
Run Code Online (Sandbox Code Playgroud)

在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')
Run Code Online (Sandbox Code Playgroud)

我的目录结构如下所示:

替代文字

我错过了什么?settings.py不正确吗?请指教.

mic*_*mut 15

我遇到了同样的问题.我的错误是,'app'不在INSTALLED_APPS项目settings.py文件的列表中.

该错误引发错误消息,他们建议类似的错误.

line 25, in get_template TemplateDoesNotExist(template_name, chain=chain)
django.template.exceptions.TemplateDoesNotExist: authControll/index.html
Run Code Online (Sandbox Code Playgroud)

settings.py - >应用程序定义

INSTALLED_APPS = [
    ...,
    'authControll'
]
Run Code Online (Sandbox Code Playgroud)

  • 如果您刚刚开始使用 django,这可能会解决您的问题。 (3认同)

小智 6

Django 有一种模式和哲学。尝试使用相同的配置,否则您必须更改 django 中的核心模式。

django 中的模板模式如下:

polls/templates/polls/index.html
Run Code Online (Sandbox Code Playgroud)

但要使用它,您必须在配置中添加已安装的应用程序:

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',]
Run Code Online (Sandbox Code Playgroud)

欲了解更多信息,请参阅:

https://docs.djangoproject.com/en/3.0/intro/tutorial02/#activating-models


zsq*_*are 5

您必须在TEMPLATE_DIRS设置中使用绝对路径。

方便的操作是,在设置的顶部插入:

import os
DIRNAME = os.path.abspath(os.path.dirname(__file__))
Run Code Online (Sandbox Code Playgroud)

然后在任何使用路径的地方使用os.path.join。例如,您TEMPLATE_DIRS将变成:

TEMPLATE_DIRS = (
    os.path.join(DIRNAME, 'site-templates/'),
)
Run Code Online (Sandbox Code Playgroud)