render_to_response 报错 TemplateDoesNotExist
我正在获取模板的路径,使用的是
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))
但是我遇到了一个错误
TemplateDoesNotExist at /test-payment-url/
E:\testapp\template\payment.html
这个错误为什么会出现呢?
编辑:我在settings.py中做了以下更改,现在能够找到模板了,但在生产环境中我不能硬编码这个路径,有什么建议吗?
TEMPLATE_DIRS = ("E:/testapp" )
4 个回答
2
我这里没有Django,但我觉得你应该用 / 而不是 \\ ?
Python可以帮助你在不同操作系统之间处理斜杠的问题。
11
顺便说一下,有个棘手的事情是,Django会抛出一个叫TemplateDoesNotExist
的错误,即使你渲染的模板里面包含了一个不存在的模板,比如{% include "some/template.html" %}
... 这个知识点让我浪费了一些时间和精力。
23
看起来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.html
或者E:\path\to\project\templates\subdir\payment.html
。关键是这些模板必须在我们在settings.py中指定的目录里。