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

时间:2018-01-29 04:47:23

标签: python flask

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

  

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

这是我的Flask Code:

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代码(此代码可能有Bugs但现在烧瓶显示错误):

    <!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>

1 个答案:

答案 0 :(得分:2)

您的错误位于操作=&#34; {{url_for(索引)}}&#34; 。您使用索引作为变量,但您没有向模板传递任何内容。我想你想得到索引的url,然后用单引号包装 index ,它会正常工作,即:action =&#34; {{url_for(&#39; index&# 39; )}}&#34;。