编辑
如果我调用request.files['file']
,我会得到文件对象,但form.validate_on_submit()
仍然失败。如果请求中有文件对象,为什么会失败?
我有三个文件:
表单.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 %}