在python app-engine django 1.2中渲染绝对路径时出现TemplateDoesNotExist
由于App Engine的警告
你正在使用默认的Django版本(0.96)。在不久的将来,App Engine的更新会改变默认的Django版本。请使用use_library()来明确选择一个Django版本。想了解更多信息,可以查看这个链接
我在main.py的顶部添加了两行代码
from google.appengine.dist import use_library
use_library("django", "1.2")
这段代码完全搞坏了我的应用,出现了这个错误
File "/home/adel/Software/google_appengine/lib/django_1_2/django/template/loader.py", line 138, in find_template
raise TemplateDoesNotExist(name)
TemplateDoesNotExist: /home/adel/Workspace/jeeneo/site/Common/templates/en_US/template.html
我在网上搜索,发现有开发者遇到类似的问题,关于Django不再支持相对路径。在我的情况下,我使用的是绝对路径,我的代码结构是这样的
site/
Frontpage/
template/en_US/index.html
index.py
Events/
template/en_US/event.html
template/en_US/create.html
event.py
create.py
Common/
template/en_US/template.html
template.py
每个类都继承了Template类,像这样
from Common import Template
class Event(Template):
def get(self):
然后调用
self.render(__file__, "event.html")
为了渲染HTML文件,render函数内部有这些内容
def render(self, path, html):
self.base = self.get_base()
email = None
if self.user:
self.auth_url = users.create_logout_url("/")
email = self.user.email
else:
self.auth_url = users.create_login_url(self.request.uri)
self.template.update({
"base": self.base,
"user": self.user,
"lang": self.lang,
"template_html" : os.path.join(os.path.dirname(__file__), "templates/%s/template.html" % self.lang),
"email": email,
"auth_url": self.auth_url
})
html = os.path.join(os.path.dirname(path), "templates/%s/%s" % (self.lang, html))
self.template.update(self.data)
self.response.out.write(template.render(html, self.template))
而HTML文件(event.html)包含这段代码
{% extends template_html %}
我脑海中有两个解决方案,也许可以重构所有内容,把所有模板放在一个文件夹里,或者在App Engine上本地安装Django 0.96……但我很确定一定有更简单的解决办法。
1 个回答
1
我遇到过一些类似的问题,这里分享一些解决方法:
当你使用App引擎的 template.render
时,它会把 TEMPLATE_DIRS
设置为你正在渲染的模板所在的文件夹。在Django 1.2中,extends
标签会检查被包含的模板是否在 TEMPLATE_DIRS
目录下。如果这些模板在上级目录或者同级目录下,它就会出错。
我找到的解决办法是,不使用App引擎的 template.render
,而是用Django的Template类自己写一个渲染方法。然后我还需要把 TEMPLATE_DIRS
设置为我的项目根目录。
这段记忆是我在1.4.2版本时的情况,当时我第一次研究这个问题——虽然之后的版本可能有所变化,但我的解决方法依然有效。