【问题标题】:jinja2.exceptions.TemplateNotFound why does this keep popping up?jinja2.exceptions.TemplateNotFound 为什么会不断弹出?
【发布时间】:2020-06-19 09:40:17
【问题描述】:

这是我保存在下载中的代码 pro.py:

 from flask import Flask, render_template, flash, session, redirect, url_for
    from flask_wtf import FlaskForm
    from wtforms import StringField,SubmitField

app = Flask(__name__)

app.config['SECRET_KEY'] = 'kmkey'

class SimpleForm(FlaskForm):

    breed = StringField('What breed are you?')
    submit= SubmitField('Click Me')

@app.route('/',methods=['GET','POST'])
def imp():

    form = SimpleForm()

    if form.validate_on_submit():
        session['breed'] = form.breed.data
        flash(f"You just changed your breed to: {session['breed']}")

        return redirect(url_for('imp'))

    return render_template('imp.html',form=form)

if __name__ == '__main__':
    app.run(debug=True)

这是我保存在模板文件夹中的 html 代码 imp.html,该文件夹位于 Downloads 内:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
     {% for mess in get_flashed_messages() %}
     <div class="alert alert-warning alert-dismissible fade show" role='alert'>
        <button type="button" class="fade close" data-dismiss='alert' aria-label='close' >
          <span aria-hidden='true'>&times;</span>
        </button>
        {{mess}}
     </div>

    {% endfor %}

    <form method="post">
      {{form.hidden_tag()}}
      {{form.breed.label}}{{form.breed}}
      {{form.submit()}}
    </form>
  </body>
</html>

现在,当我在 web 上运行我的 python 文件时,它会抛出一个错误,说 jinja2.exceptions.TemplateNotFound:imp.html 为什么会这样??

谁能帮我解决这个问题。

【问题讨论】:

    标签: python html flask jinja2 web-development-server


    【解决方案1】:

    您需要将其保存在templates 文件夹而不是template 文件夹中。

    【讨论】:

    • 感谢您的回复。但我只有一个澄清和;那是因为我刚刚开始了解 Flask 我只是想知道 render_template 的实际含义是什么以及为什么需要将特定的 html 文件保存在模板文件夹中
    • render_template 方法只是将 html 文件渲染到特定路径。需要将该 html 文件保存在 templates 文件夹中,因为当您启动烧瓶应用程序 app = Flask(__name__) 时,它还有一个 template_folder 参数,默认情况下是基本应用程序目录中的 templates 文件夹。如果需要,您可以更改此行为。 app = Flask(__name__, template_folder='path you want'。希望你理解这个概念。
    • 我的荣幸。如果它解决了您的问题,请将其标记为可以帮助其他访问者遇到此问题的答案。
    猜你喜欢
    • 1970-01-01
    • 2020-03-20
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多