gpt4 book ai didi

python - flask 同一页面上的多个表单

转载 作者:行者123 更新时间:2023-12-02 16:52:12 31 4
gpt4 key购买 nike

我的 Flask 应用程序出现问题,基本上我在同一个 html 页面中有两个表单,当我提交一个或另一个时,它会同时提交两个表单。有什么方法可以将它们分开,以便我可以单独提交它们吗?

@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)

最佳答案

您可以通过提交输入来区分这些表单。只需将它们设置为不同的 ID/名称,并通过检查其 ID/名称是否存在于 request.form 中来检查表单提交是否源自此特定表单。 .

第一种形式:

<input type="submit" id="form-submit" name="form-submit" value="Submit form">

第二个:

<input type="submit" id="form2-submit" name="form2-submit" value="Submit form2">

在你看来逻辑:

@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)

关于python - flask 同一页面上的多个表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58122969/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com