[Flask] Multiple forms linked to a single submit button
Kyle Lawlor
klawlor419 at gmail.com
Thu Sep 10 20:16:35 CEST 2015
Hi all,
I am very new to Flask and web development. I have been working through the
Flask book by Grinberg. I am having trouble with the following sort of
thing. I would like to have multiple string fields triggered by the same
submit button. I would like to have all of the string fields as required.
Here is my Flask script:
from flask import Flask
from flask import render_template, request
from flask_wtf import Form
from wtforms import StringField
from wtforms.validators import Required
app = Flask(__name__)
app.config['SECRET_KEY'] = 'string'
class MyForm(Form):
name = StringField('name', validators=[Required()])
@app.route('/',methods=['GET','POST'])
def index():
name1 = None
form1 = MyForm(prefix='form1')
name2 = None
form2 = MyForm(prefix='form2')
print request
if form1.validate_on_submit():
name1 = form1.name.data
print name1
form1.name.data = ""
elif form2.validate_on_submit():
name2 = form2.name.data
print name2
form2.name.data=""
return render_template('index.html',
form1=form1,
form2=form2)
if __name__=='__main__':
app.run(host='0.0.0.0',debug=True)
Here is my templates/index.html:
<!doctype html>
<form method="POST" action="/">
{{ form1.csrf_token }}
{{ form1.name.label }} {{ form1.name(size=20) }}
<input type="submit" name='btn' value="form1">
</form>
<form method="POST" action="/">
{{ form2.csrf_token }}
{{ form2.name.label }} {{ form2.name(size=20) }}
<input type="submit" name='btn' value="form2">
</form>
</html>
Right now I have two buttons that do not properly submit data for each
field, that is answered here though
<http://stackoverflow.com/questions/18290142/multiple-forms-in-a-single-page-using-flask-and-wtforms/18293534#18293534>.
Again, I would like to have a single input button that links to both
required string fields.
Here is pseudocode of how I see it happening :
<!doctype html>
<form method="POST" input-id="trigger" action="/">
{{ form1.csrf_token }}
{{ form1.name.label }} {{ form1.name(size=20) }}
</form>
<form method="POST" input-id="trigger" action="/">
{{ form2.csrf_token }}
{{ form2.name.label }} {{ form2.name(size=20) }}
</form>
<input type="submit" name='btn' input-id="trigger" value="form2">
</html>
, where input-id="trigger" links the forms to the submit button.
I suppose this is more of an html question as written, but perhaps there
is a better way to do this in the Flask-WTForms framework.
Thanks,
Kyle
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20150910/b3153515/attachment.html>
More information about the Flask
mailing list