【问题标题】:Django throws TemplateDoesNotExistDjango 抛出 TemplateDoesNotExist
【发布时间】:2014-03-24 15:33:38
【问题描述】:

这不是我第一次遇到此错误,但通常我通过向 TEMPLATE_DIRS 元组添加模板路径来解决它,尽管这不再适合我了。这是我的 settings.py 模板 sn-p:

TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
 os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/'),
)

我安装的应用程序 sn-p:

INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
 #this is my app right here.
'boilerplate',
)

还有我在 views.py 文件中的简单代码:

from django.shortcuts import render_to_response
from django.template import RequestContext

def index(request):
 return render_to_response('test.html',context_instance=RequestContext(request))

我认为重要的是要提到我的模板文件夹放置在我的项目结构中,而不是我的应用程序的结构中。有什么想法吗?

【问题讨论】:

  • 您的模板是否在项目目录中并不重要。打印os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/')的结果是什么?
  • 另外,您是否厌倦了将绝对文件路径作为字符串放入模板元组中以查看是否有效
  • 刚刚尝试了第二个建议,它没有奏效。错误屏幕向我显示以下消息:“/home/user/PyWeb/django_backbone/templates/test.html”
  • @user1659653 我不知道你应该在路径中有空格
  • @zinking 实际上安装了一个空格。用户配置文件框隐藏的 django_backbone 中有一个下划线。尝试放大/复制它

标签: python django web backend


【解决方案1】:

这是你需要实现的文件夹结构。

myproject/
  ...
  myapp/
    views.py
    ...
    templates/
      myapp/
        mytemplate.html

这就是你在views.py中所做的事情

def index(request):
 return render_to_response('myapp/test.html',context_instance=RequestContext(request))

您的 TEMPLATE_DIRS 没问题。

阅读本文以获取更多信息:https://docs.djangoproject.com/en/1.6/intro/tutorial03/#write-views-that-actually-do-something

【讨论】:

  • 我完全忘记了这个线程。是的,我的文件夹结构错误,我在几周前解决了,但这是正确的答案。感谢发帖。
猜你喜欢
  • 1970-01-01
  • 2011-06-13
  • 2014-10-17
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
  • 2021-11-15
  • 2018-06-02
  • 2014-02-19
相关资源
最近更新 更多