【问题标题】:Flask - jinja2.exceptions.UndefinedError: 'index' is undefinedFlask - jinja2.exceptions.UndefinedError: 'index' 未定义
【发布时间】:2018-01-29 04:47:23
【问题描述】:

这是一个简单的烧瓶任务,它从用户那里选择 jpg 格式文件并保存到特定文件夹,但它给了我 这个错误:

jinja2.exceptions.UndefinedError: 'index' 未定义

这是我的烧瓶代码:

import os
from flask import Flask, render_template, request
app = Flask(__name__)
app_root = os.path.dirname(os.path.abspath(__file__))
@app.route("/")
def index():
    target = os.path.join(app_root, 'txt/')
    print(target)
    if not os.path.isdir(target):
    os.mkdir(target)

for file in request.files.getlist("mp3_file"):
    print(file)
    file_name = file.filename
    destination = '/'.join([target, file_name])
    print(destination)
    file.save(destination)

return render_template('index.html')
if __name__ == '__main__':
    app.run(debug=True)

&这是我的 HTML 代码(此代码可能有错误但现在烧瓶显示错误):

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename = 
    'bootstrap.css') }}" /><!-- ../static/bootstrap.css -->
    </head>
    <body background="Bg.jpg">
    <center>
     <form method="post" enctype="multipart/form-data" action="{{ url_for(index) }}">
        <table class="table table-hover" style="width:100px; background-color:rgba(102,102,102,0.9); border-radius:10px; margin:100px">
            <tr>
               <td class="text-right"><label class="text-white" style="margin-top:4%">Upload Your Audio file here: </label></td> 
               <td><input name="mp3_file" type="file" value="" class="text-white btn" required></td>
            </tr>
            <tr>
               <td colspan="2"><input type="submit" name="submit_btn" value="Submit" class="btn btn-dark" style="margin-left:45%" /></td>
            </tr>
            <tr>
                <td colspan="2">{% if file %}<textarea name="answer" rows="10" cols="100" content="{{ file }}" ></textarea>{% else %} <textarea name="answer" rows="10" cols="100" ></textarea> {% endif %}</td>
            </tr>
        </table>
    </form>
</center>
</body>
</html>

【问题讨论】:

  • action="{{ url_for(index) }}" index 定义在哪里?
  • 你的意思是这样 {{ url_for(index.html) }}

标签: python flask


【解决方案1】:

您的错误在于 action="{{ url_for(index) }}"。您正在使用 index 作为变量,但您没有将任何内容传递给模板。我想您想获取索引的网址,然后用单引号将 index 包裹起来,它会正常工作,即: action="{{ url_for('index') } }”。

【讨论】:

  • 您应该将背景图片移动到静态文件夹,并将链接从“Bg.jpg”更改为“/static/Bg.jpg”。有关烧瓶中静态文件的更多知识,请查看here
猜你喜欢
  • 2021-08-21
  • 2020-12-24
  • 2019-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-11
相关资源
最近更新 更多