Django找不到模板

时间:2012-07-10 21:41:58

标签: python django django-templates

我知道很多人都问过这个问题,但是尽管硬编码了我的模板目录的路径,我似乎无法让Django找到我的模板。

这是settings.py

TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
#django.template.loaders.eggs.Loader',
)

TEMPLATE_DIRS = (
    "/Users/full/path/to/marketing_site/templates",
)

这是views.py文件:

def static (request, feature_page):

# this will get the appropriate feature page template.
template = loader.get_template('features/pricing.html')
c = RequestContext(request,{
})
return HttpResponse(template.render(c))

主文件夹内是templates文件夹和app文件夹。我用来将应用程序放在settings.py所在的文件夹中,但是看起来django 1.4已经改变了默认的文件结构。

我的错误是:

TemplateDoesNotExist at /features/pricing 

Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
/Library/Python/2.7/site-packages/django/contrib/auth/templates/feature_pricing.html (File does not exist)

更新:
我的网页日志将TEMPLATE_DIRS列为()。

如果我在TEMPLATE_DIRS的settings.py页面上放置一个print语句,我会正确地得到TEMPLATE_DIRS的打印输出......所以不知道TEMPLATE_DIRS是否被使用(从它的外观看)

4 个答案:

答案 0 :(得分:8)

我在settings.py

中添加了额外的TEMPLATE_DIR

:(

答案 1 :(得分:4)

最好为路径变量设置相对路径。您可以这样设置:

import os

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

...

...

TEMPLATE_DIRS = (
    PATH_PROJECT + '/templates/'
)

另外假设您正在使用Windows,您可能想尝试:

TEMPLATE_DIRS = (
"C:/Users/full/path/to/marketing_site/templates",
)

答案 2 :(得分:1)

我打赌/Users/full/path/to/marketing_site/templates不包含features目录,或/Users/full/path/to/marketing_site/templates/features不包含pricing.html文件。

根据您的评论,您似乎在调用loader.get_template('feature_pricing.‌​html'),而不是使用'feature/pricing.html'

编辑:我之前没有注意到这一点:

  

主文件夹内是templates文件夹和app文件夹。我用来将应用程序放在settings.py所在的文件夹中,但是看起来django 1.4已经改变了默认的文件结构。

这可能导致问题。更改目录结构以匹配1.4 Django约定。您可以只重新创建项目,将相关设置复制到新创建的settings.py中,然后复制所有文件。

答案 3 :(得分:1)

尝试将项目路径添加到django.wsgi

import os
import sys

paths = ('path/to/project/',
        'path/to/more /included/directories/',
    )

for path in paths:
    if path not in sys.path:
       sys.path.append(path)

os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()