My app looks as follows:
from flask import Flask, render_template, request
from flask_wtf import FlaskForm
from wtforms import IntegerField, FileField
app = Flask(__name__)
app.secret_key = 'secret'
class MyForm(FlaskForm):
myFile = FileField('File')
myInt = IntegerField('Number')
@app.route('/', methods = ['POST','GET'])
def home():
form = MyForm()
if request.method == 'GET':
return render_template('index.html', form=form)
else:
myFile = form.myFile
myInt = form.myInt
print("The file is {} and the int is {}".format(myFile.data, myInt.data))
return render_template('index.html', form=form)
if __name__ == "__main__":
app.run(debug=True)
and my HTML file is:
<html>
<body>
<form action="/" method="POST" enctype="multipart/form-data">
{{ form.myFile.label }} {{ form.myFile }}<br>
{{ form.myInt.label }} {{ form.myInt }}<br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
If I select a file, enter a 4 in the IntegerField and press Submit, I get the following print:
The file is <FileStorage: 'file.txt' ('text/plain')> and the int is 4
After the page reloads, I still see the 4 I entered, but I no longer see the name of the file next to the Browse button. Unsurprisingly, if I click Submit again, I get:
The file is <FileStorage: '' ('application/octet-stream')> and the int is 4
How can I pass on the file name after hitting the button? Even if it's not displayed to the user, I would like the value to remain stored in the form.
I know I can save the file, but I would like to avoid that, and I don't understand why FileField's behavior is so different from that of IntegerField.