编辑
如果我调用request.files['file']
,我将得到文件对象,但是form.validate_on_submit()
仍然失败。如果请求中存在文件对象,为什么会失败?
我有三个文件:
forms.py
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired
class ExcelForm(FlaskForm):
excel_file = FileField(validators=[
FileRequired()
])
webapp.py
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)
templates \ upload.html
{% 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 %}
我可以毫无问题地访问localhost:5000/upload
。我单击浏览按钮,选择我的文件,然后单击提交按钮。
在webapp.py
upload
函数中,form.validate_on_submit()
失败,并给我一个错误,提示{'excel_file': ['This field is required.']}
。有人可以告诉我我在做什么错吗?
我也不想在本地保存文件以供以后阅读。
您需要以flask-wtforms指定的方式呈现表单字段。
实际上是从他们的文档中复制的...
{% 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
{% 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 %}