代码之家  ›  专栏  ›  技术社区  ›  duffymo

Django找不到我的模板

  •  6
  • duffymo  · 技术社区  · 14 年前

    我在Windowsxpsp3上运行python 2.6.1和django 1.2.1。我正在使用JetBrains Pycharm 1.0创建和部署我的Django应用程序。

    我对python比较缺乏经验,我开始学习django,并从网站“编写你的第一个django应用程序”——投票应用程序开始学习。我被卡住了 part 3 .

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

    当我开始“写一些真正有用的视图”时,我遇到了障碍。

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

    1. 向views.py中添加新方法(注意-模板已从“pollings/index.html”中准备就绪):
    2. 将index.html模板添加到 site-templates/polls/ 文件夹
    3. 将settings.py修改为指向 site-templates 文件夹

    这是我的视图中的代码.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))
    

    这是“我的设置”中的一行。

    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')
    

    我的目录结构如下:

    alt text

    我错过了什么?settings.py是否不正确?请告知。

    4 回复  |  直到 8 年前
        1
  •  12
  •   michael-mammut    8 年前

    我也面临同样的问题。在我的案例中,错误是“应用程序”不在 INSTALLED_APPS 在project settings.py文件中列出。

    错误会引发一条错误消息,提示类似的错误。

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

    settings.py-->应用程序定义

    INSTALLED_APPS = [
        ...,
        'authControll'
    ]
    
        2
  •  3
  •   Jordan Reiter    14 年前

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

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

    import os
    DIRNAME = os.path.abspath(os.path.dirname(__file__))
    

    然后在你使用路径的任何地方,使用 os.path.join . 例如,您的 模板目录 会变成:

    TEMPLATE_DIRS = (
        os.path.join(DIRNAME, 'site-templates/'),
    )
    
        3
  •  0
  •   songyuanyao    11 年前

    这肯定能解决这个问题,而不是上面所有的,试着只在下面加一行。 settings.py :

    TEMPLATE_DIRS = (
        "appname/templates",
    )
    
        4
  •  -6
  •   seriyPS    14 年前

    http://docs.djangoproject.com/en/1.2/ref/templates/api/#loading-templates @zsquare答案的小修复:

    import os
    DIRNAME = os.path.abspath(os.path.dirname(__file__))
    
    TEMPLATE_DIRS = ( DIRNAME+'/site-templates/' )