Reputation: 2520
I got a problem with my flask application, basically I have two forms in the same html page and when I submit one or the other it submits both of them at the same time. Is there any way that I could separate them somehow, so I can submit them individually?
@app.route('/smtp/', methods=['GET', 'POST'])
def smtp():
form = UpdateSMTPForm()
form2 = UpdateEmailAddress()
query = Email.query.all()
if form.validate_on_submit():
email = str(form.email.data)
password = str(form.password.data)
server = str(form.server.data)
port = str(form.port.data)
if tools.test_email(server, port, email, password):
CONFIG['SMTP']['server'] = server
CONFIG['SMTP']['port'] = port
CONFIG['SMTP']['username'] = email
CONFIG['SMTP']['password'] = password
with open('config.json', 'w') as f:
f.write(json.dumps(CONFIG))
f.close()
else:
form.server.errors.append("Invalid account, be sure that you have less secure app access turned on or try with a gmail account")
if form2.validate_on_submit():
print('form2 email updated {}'.format(form2.email))
else:
print('cannot validate the second form')
return render_template('smtp.html', config=CONFIG['SMTP'], query=query, form=form, form2=form2)
Upvotes: 2
Views: 7453
Reputation: 1863
You can distinguish these forms by the submit input. Just set them different id/name and check if form submission origins from this particular form by checking if its id/name is present in request.form
.
In the first form:
<input type="submit" id="form-submit" name="form-submit" value="Submit form">
And the second one:
<input type="submit" id="form2-submit" name="form2-submit" value="Submit form2">
And logic in your view:
@app.route('/smtp/', methods=['GET', 'POST'])
def smtp():
form = UpdateSMTPForm()
form2 = UpdateEmailAddress()
query = Email.query.all()
if "form-submit" in request.form and form.validate_on_submit():
email = str(form.email.data)
password = str(form.password.data)
server = str(form.server.data)
port = str(form.port.data)
if tools.test_email(server, port, email, password):
CONFIG['SMTP']['server'] = server
CONFIG['SMTP']['port'] = port
CONFIG['SMTP']['username'] = email
CONFIG['SMTP']['password'] = password
with open('config.json', 'w') as f:
f.write(json.dumps(CONFIG))
f.close()
else:
form.server.errors.append("Invalid account, be sure that you have less secure app access turned on or try with a gmail account")
if "form2-submit" in request.form and form2.validate_on_submit():
print('form2 email updated {}'.format(form2.email))
else:
print('cannot validate the second form')
return render_template('smtp.html', config=CONFIG['SMTP'], query=query, form=form, form2=form2)
Upvotes: 8