Python 为什么flask_wtf.FlaskForm上载文件时出现错误,表示文件未上载?
编辑 如果我调用request.files['file'],我会得到file对象,但是form.validate\u on\u submit仍然失败。如果请求中存在文件对象,为什么会失败 我有三个文件: forms.py webapp.py 模板\upload.html 我可以访问localhost:5000/上传,没有问题。我单击浏览按钮,选择我的文件,然后单击提交按钮 在webapp.py upload函数中,form.validate_on_submit失败,并显示错误{'excel_file':['This field is required.]}。有人能告诉我我做错了什么吗Python 为什么flask_wtf.FlaskForm上载文件时出现错误,表示文件未上载?,python,flask,flask-restful,Python,Flask,Flask Restful,编辑 如果我调用request.files['file'],我会得到file对象,但是form.validate\u on\u submit仍然失败。如果请求中存在文件对象,为什么会失败 我有三个文件: forms.py webapp.py 模板\upload.html 我可以访问localhost:5000/上传,没有问题。我单击浏览按钮,选择我的文件,然后单击提交按钮 在webapp.py upload函数中,form.validate_on_submit失败,并显示错误{'excel_fi
我也不想将文件保存在本地以便以后读取。您需要以指定的方式呈现表单字段 实际上是从他们的文档中复制的
{% extends "layout.html" %}
{% from "_formhelpers.html" import render_field %}
{% block content %}
<form method = "POST" enctype = "multipart/form-data">
{{ form.hidden_tag() }}
{{ render_field(form.file) }}
{{ render_field(form.submit) }} <!-- add a submit button to your form -->
</form>
{% endblock content %}
然后创建宏
_formhelpers.html
我尝试了你的建议,在Excel表单中添加了一个提交按钮。我仍然得到相同的表单。错误是没有文件。
from flask import Flask, render_template, redirect, url_for, request
from forms import ExcelForm
import pandas as pd
app = Flask(__name__)
app.config['SECRET_KEY'] = '314159265358'
@app.route('/', methods=['GET', 'POST'])
def upload():
form = ExcelForm(request.form)
if request.method == 'POST' and form.validate_on_submit():
df = pd.read_csv(form.excel_file.data)
print(df.head())
return redirect(url_for('hello', name=form.excel_file.data))
return render_template('upload.html', form=form)
@app.route('/hello/<name>')
def hello(name):
return 'hello' + name
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
{% extends "layout.html" %}
{% block content %}
<form method = "POST" enctype = "multipart/form-data">
{{ form.hidden_tag() }}
<input type = "file" name = "file" />
<input type = "submit"/>
</form>
{% endblock content %}
{% extends "layout.html" %}
{% from "_formhelpers.html" import render_field %}
{% block content %}
<form method = "POST" enctype = "multipart/form-data">
{{ form.hidden_tag() }}
{{ render_field(form.file) }}
{{ render_field(form.submit) }} <!-- add a submit button to your form -->
</form>
{% endblock content %}
{% macro render_field(field) %}
<dt>{{ field.label }}
<dd>{{ field(**kwargs)|safe }}
{% if field.errors %}
<ul class=errors>
{% for error in field.errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
</dd>
{% endmacro %}