Django模板不存在错误,尽管它显示“文件存在”

2024-10-05 17:40:35 发布

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

我无法在Django 1.7中呈现任何html页面。我的'index.html'在'project/seatalloc/templates/index.html'中,而我的view.py在project/seatalloc/views.py中,看起来像:

 def index(request):
       return render(request, 'index.html', dirs=('templates',)) 

project/project/settings.py设置了模板目录:

TEMPLATE_DIRS = (
    '/Users/Palak/Desktop/academics/sem3/cs251/lab11/project/seatalloc/templates',

)

网址.py:

urlpatterns = patterns('',
    url(r'^seatalloc/', include('seatalloc.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

Template loader

我试着严格遵循文档,但是不知道Django是否检测到该文件,为什么我在/seatalloc/error获取TemplateDoesNotExist。我是刚到Django的,有人能帮忙吗。


Tags: djangopyprojectviewurlindexincludeadmin
3条回答

像这样试试

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = (
     os.path.join(BASE_DIR, 'templates/'),
)

如果-在您的例子中-您得到了一个模板不存在的错误,并且调试页面在所讨论的模板旁边声明“文件存在”,这通常(总是?)表示此模板引用了另一个找不到的模板。

在您的例子中,index.html包含一个语句({% extends %}, {% include %}, ...),该语句引用另一个模板Django找不到。不幸的是,从Django 1.8.3开始,调试页面总是命名基本模板,而不是Django找不到的模板。

首先,不要在settings.py的template dirs中使用静态路径(固定路径),请使用:

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

TEMPLATE_DIRS = (
      BASE_DIR +'/Templates',


  )

模板目录应该在项目目录中,即manage.py文件所在的目录中。

在view.py中使用render_to_response,而不仅仅是render

return  render_to_response("index.html") 

相关问题 更多 >