Python 即使模板文件存在,Flask 也会引发 TemplateNotFound 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23327293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask raises TemplateNotFound error even though template file exists
提问by Srdan Ristic
I am trying to render the file home.html
. The file exists in my project, but I keep getting jinja2.exceptions.TemplateNotFound: home.html
when I try to render it. Why can't Flask find my template?
我正在尝试呈现文件home.html
。该文件存在于我的项目中,但是jinja2.exceptions.TemplateNotFound: home.html
当我尝试渲染它时,我不断收到。为什么 Flask 找不到我的模板?
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
/myproject
app.py
home.html
采纳答案by Martijn Pieters
You must create your template files in the correct location; in the templates
subdirectory next to your python module.
您必须在正确的位置创建模板文件;在templates
python 模块旁边的子目录中。
The error indicates that there is no home.html
file in the templates/
directory. Make sure you created that directory in the same directory as your python module, and that you did in fact put a home.html
file in that subdirectory. If your app is a package, the templates folder should be created insidethe package.
该错误表明目录中没有home.html
文件templates/
。确保您在与 python 模块相同的目录中创建了该目录,并且您确实home.html
在该子目录中放置了一个文件。如果您的应用程序是一个包,则应在包内创建模板文件夹。
myproject/
app.py
templates/
home.html
myproject/
mypackage/
__init__.py
templates/
home.html
Alternatively, if you named your templates folder something other than templates
and don't want to rename it to the default, you can tell Flask to use that other directory.
或者,如果您将模板文件夹命名为其他名称templates
并且不想将其重命名为默认值,则可以告诉 Flask 使用该其他目录。
app = Flask(__name__, template_folder='template') # still relative to module
You can ask Flask to explain how it tried to find a given template, by setting the EXPLAIN_TEMPLATE_LOADING
optionto True
. For every template loaded, you'll get a report logged to the Flask app.logger
, at level INFO
.
你可以问烧瓶解释它是如何试图找到一个给定的模板,通过设置EXPLAIN_TEMPLATE_LOADING
选项来True
。对于加载的每个模板,您都会在Flaskapp.logger
级别获得一个报告INFO
。
This is what it looks like when a search is successful; in this example the foo/bar.html
template extends the base.html
template, so there are two searches:
这是搜索成功时的样子;在这个例子中,foo/bar.html
模板扩展了base.html
模板,所以有两个搜索:
[2019-06-15 16:03:39,197] INFO in debughelpers: Locating template "foo/bar.html":
1: trying loader of application "flaskpackagename"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /.../project/flaskpackagename/templates
-> found ('/.../project/flaskpackagename/templates/foo/bar.html')
[2019-06-15 16:03:39,203] INFO in debughelpers: Locating template "base.html":
1: trying loader of application "flaskpackagename"
class: jinja2.loaders.FileSystemLoader
encoding: 'utf-8'
followlinks: False
searchpath:
- /.../project/flaskpackagename/templates
-> found ('/.../project/flaskpackagename/templates/base.html')
Blueprints can register their own template directoriestoo, but this is not a requirement if you are using blueprints to make it easier to split a larger project across logical units. The main Flask app template directory is always searched first even when using additional paths per blueprint.
蓝图也可以注册它们自己的模板目录,但是如果您使用蓝图来更轻松地跨逻辑单元拆分较大的项目,则这不是必需的。即使在每个蓝图使用附加路径时,也始终首先搜索主 Flask 应用程序模板目录。
回答by Eric
Check that:
检查:
- the template file has the right name
- the template file is in a subdirectory called
templates
- the name you pass to
render_template
is relative to the template directory (index.html
would be directly in the templates directory,auth/login.html
would be under the auth directory in the templates directory.) - you either do not have a subdirectory with the same name as your app, or the templates directory is inside that subdir.
- 模板文件具有正确的名称
- 模板文件位于名为
templates
- 您传递给的名称
render_template
是相对于模板目录的(index.html
将直接在模板目录中,auth/login.html
将在模板目录中的 auth 目录下。) - 您要么没有与您的应用程序同名的子目录,要么模板目录位于该子目录中。
If that doesn't work, turn on debugging (app.debug = True
) which might help figure out what's wrong.
如果这不起作用,请打开调试 ( app.debug = True
),这可能有助于找出问题所在。
回答by Fran?ois Breton
I don't know why, but I had to use the following folder structure instead. I put "templates" one level up.
我不知道为什么,但我不得不使用以下文件夹结构。我把“模板”上一层。
project/
app/
hello.py
static/
main.css
templates/
home.html
venv/
This probably indicates a misconfiguration elsewhere, but I couldn't figure out what that was and this worked.
这可能表明其他地方的配置错误,但我无法弄清楚那是什么并且这有效。
回答by Madhusudan chowdary
You need to put all you .html
files in the templatefolder next to your python module. And if there are any images that you are using in your html files then you need put all your files in the folder named static
您需要将所有.html
文件放在python 模块旁边的模板文件夹中。如果您在 html 文件中使用了任何图像,那么您需要将所有文件放在名为static的文件夹中
In the following Structure
在以下结构中
project/
hello.py
static/
image.jpg
style.css
templates/
homepage.html
virtual/
filename.json
回答by Shubham Khaire
I had the same error turns out the only thing i did wrong was to name my 'templates' folder,'template' without 's'. After changing that it worked fine,dont know why its a thing but it is.
我遇到了同样的错误,结果我唯一做错的是命名我的“模板”文件夹,“模板”没有“s”。更改后它工作正常,不知道为什么它是一件事,但它是。
回答by Akshay Karande
I think Flask uses the directory templates by default. So your code should be suppose this is your hello.py
我认为 Flask 默认使用目录模板。所以你的代码应该假设这是你的 hello.py
from flask import Flask,render_template
app=Flask(__name__,template_folder='template')
@app.route("/")
def home():
return render_template('home.html')
@app.route("/about/")
def about():
return render_template('about.html')
if __name__=="__main__":
app.run(debug=True)
And you work space structure like
你的工作空间结构就像
project/
hello.py
template/
home.html
about.html
static/
js/
main.js
css/
main.css
also you have create two html files with name of home.html and about.html and put those files in template folder.
您还创建了两个名为 home.html 和 about.html 的 html 文件,并将这些文件放在模板文件夹中。
回答by Atal Kumar
When render_template() function is used it tries to search for template in the folder called templates and it throws error jinja2.exceptions.TemplateNotFound when :
当使用 render_template() 函数时,它会尝试在名为 templates 的文件夹中搜索模板,并在以下情况下抛出错误 jinja2.exceptions.TemplateNotFound :
- the html file do not exist or
- when templates folder do not exist
- html 文件不存在或
- 当模板文件夹不存在时
To solve the problem :
解决问题:
create a folder with name templates in the same directory where the python file is located and place the html file created in the templates folder.
在python文件所在的同一目录中创建一个名为templates的文件夹,并将创建的html文件放在templates文件夹中。
回答by Noone
(Please note that the above accepted Answer provided for file/project structure is absolutely correct.)
(请注意,上面为文件/项目结构提供的公认答案是绝对正确的。)
Also..
还..
In addition to properly setting up the project file structure, we have to tell flask to look in the appropriate level of the directory hierarchy.
除了正确设置项目文件结构之外,我们还必须告诉 flask 在目录层次结构的适当级别中查找。
for example..
例如..
app = Flask(__name__, template_folder='../templates')
app = Flask(__name__, template_folder='../templates', static_folder='../static')
Starting with ../
moves one directory backwards and starts there.
从开始../
向后移动一个目录并从那里开始。
Starting with ../../
moves two directories backwards and starts there (and so on...).
从开始../../
向后移动两个目录并从那里开始(依此类推......)。
Hope this helps
希望这可以帮助
回答by Max
Another alternative is to set the root_path
which fixes the problem both for templates and static folders.
另一种选择是设置root_path
解决模板和静态文件夹的问题。
root_path = Path(sys.executable).parent if getattr(sys, 'frozen', False) else Path(__file__).parent
app = Flask(__name__.split('.')[0], root_path=root_path)
If you render templates directly via Jinja2
, then you write:
如果你直接通过 渲染模板Jinja2
,那么你写:
ENV = jinja2.Environment(loader=jinja2.FileSystemLoader(str(root_path / 'templates')))
template = ENV.get_template(your_template_name)
回答by Yuriy Pozniak
If you run your code from an installed package, make sure template files are present in directory <python root>/lib/site-packages/your-package/templates
.
如果从已安装的包运行代码,请确保模板文件存在于<python root>/lib/site-packages/your-package/templates
.
Some details:
一些细节:
In my case I was trying to run examples of project flask_simple_uiand jinja
would always say
就我而言,我试图运行项目flask_simple_ui 的示例,并且jinja
总是说
jinja2.exceptions.TemplateNotFound: form.html
jinja2.exceptions.TemplateNotFound: form.html
The trick was that sample program would import installed package flask_simple_ui
. And ninja
being used from inside that package is using as root directory for lookup the package path, in my case ...python/lib/site-packages/flask_simple_ui
, instead of os.getcwd()
as one would expect.
诀窍是示例程序将导入已安装的包flask_simple_ui
。并且ninja
从该包内部使用是用作查找包路径的根目录,在我的情况下...python/lib/site-packages/flask_simple_ui
,而不是os.getcwd()
像人们期望的那样。
To my bad luck, setup.py
has a bug and doesn't copy any html files, including the missing form.html
. Once I fixed setup.py
, the problem with TemplateNotFoundvanished.
不幸的是,setup.py
有一个错误并且不会复制任何 html 文件,包括丢失的form.html
. 一旦我修复setup.py
了,TemplateNotFound的问题就消失了。
I hope it helps someone.
我希望它可以帮助某人。