render_to_response给出了TemplateDoesNotExist

时间:2009-12-24 06:46:26

标签: python django django-templates

我正在使用

获取模板的路径
paymenthtml = os.path.join(os.path.dirname(__file__), 'template\\payment.html')

并在另一个应用程序中调用它 paymenthtml被复制到payment_template

return render_to_response(self.payment_template, self.context, RequestContext(self.request))

但我收到错误

  

在/ test-payment-url /

上的TemplateDoesNotExist      

E:\ testapp \模板\ payment.html

为什么会出现错误?

编辑:我在settings.py中进行了以下更改,它能够找到模板,但我不能硬编码生产中的路径,任何线索?

TEMPLATE_DIRS = ("E:/testapp" )

4 个答案:

答案 0 :(得分:22)

似乎Django只会在TEMPLATE_DIRS中定义的目录中加载模板,即使它们存在于其他地方。

在settings.py中尝试此操作:

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
# Other settings...
TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, "templates"),
)

然后在视图中:

return render_to_response("payment.html", self.context, RequestContext(self.request))
# or
return render_to_response("subdir/payment.html", self.context, RequestContext(self.request))

这会呈现E:\path\to\project\templates\payment.htmlE:\path\to\project\templates\subdir\payment.html。关键是它们位于我们在settings.py。

中指定的目录中

答案 1 :(得分:11)

顺便说一句:一个棘手的问题是,即使渲染的模板包含一个不存在的模板,django也会抛出TemplateDoesNotExist ...... {% include "some/template.html" %}这个知识花了我一些时间和神经。

答案 2 :(得分:2)

我这里没有django,但我认为你应该使用/而不是\\?

python可以帮助你解决跨操作系统的斜杠

答案 3 :(得分:1)

某些您的系统上是否存在此文件?

  

E:\testapp\template\payment.html

此错误消息非常简单,当Django尝试按文件系统上的路径查找模板文件时看不到它。

如果文件存在,则下一步是检查该文件和目录的权限,以确保这不是权限问题。如果您的E:驱动器是某个网络共享的映射网络驱动器,那么您还需要检查共享权限。