render_to_response给出了TemplateDoesNotExist

dha*_*val 8 python django django-templates

我正在使用模板的路径

paymenthtml = os.path.join(os.path.dirname(__file__), 'template\\payment.html')
Run Code Online (Sandbox Code Playgroud)

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

return render_to_response(self.payment_template, self.context, RequestContext(self.request))
Run Code Online (Sandbox Code Playgroud)

但我得到错误

TemplateDoesNotExist at/test-payment-url /

E:\ testapp \模板\ payment.html

为什么会出现错误?

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

TEMPLATE_DIRS = ("E:/testapp" )
Run Code Online (Sandbox Code Playgroud)

Joh*_*ebs 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"),
)
Run Code Online (Sandbox Code Playgroud)

然后在视图中:

return render_to_response("payment.html", self.context, RequestContext(self.request))
# or
return render_to_response("subdir/payment.html", self.context, RequestContext(self.request))
Run Code Online (Sandbox Code Playgroud)

这将呈现E:\path\to\project\templates\payment.htmlE:\path\to\project\templates\subdir\payment.html.关键是它们位于我们在settings.py中指定的目录中.

  • 这是一个可靠的方法,但我想添加一些关于Django如何加载模板的信息.它将按照它们列出的顺序查看TEMPLATE_DIRS变量中列出的目录.将使用它找到的第一个匹配项.之后,Django将查看app.templates下的各种app模块并从那里加载."级联"样式加载非常方便有选择地从可重用应用程序等替换模板. (5认同)

pcv*_*pcv 11

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

  • 只是一个路人想说:谢谢. (2认同)