gpt4 book ai didi

html - Flask 多个提交按钮

转载 作者:行者123 更新时间:2023-12-04 16:44:13 27 4
gpt4 key购买 nike

我正在使用 flask 和 jinja2 创建一个简单的网络应用程序来提供一个简单的 sklearn 预测算法。

在我的 html 中,我需要获取 4 个变量:client id、textid、textid1、textid2

当我将所有内容都连接到一个提交按钮时,它目前可以正常工作。但我想要两个提交按钮,让客户端 id 在页面顶部提交,在页面底部提交 textid 内容。当我尝试使用两个提交按钮时,它会导致页面刷新并且我无法将客户端 ID 连接到 3 个 textid 变量。

    <div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>
<form method="POST">
<input name="text", id='text', placeholder="Client ID #", value="{{ client_id|round|int }}" >
<br>
<label>Enter 3 suggestions</label>
<br>
<input name="textid", placeholder="Suggested Model ID #", value="{{ request.form['textid'] }}"/>
<input name="textid1", placeholder="Suggested Model ID #", value="{{ request.form['textid1'] }}"/>
<input name="textid2", placeholder="Suggested Model ID #", value="{{ request.form['textid2'] }}"/>

<input type="submit" >
</form>
</div>

我只是像这样把它放在 flask 里:

@app.route('/suggestion', methods=['GET', 'POST'])
def with_suggestions():

try:
client_id=request.form['text']

except:
#custom function when client id is not entered to get random one
client_id = recommender.random_client_id()
try:
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
#other functional code after this

如何拆分 html 以获得两个提交按钮?谢谢!!

最佳答案

现在您已经更新了代码,您需要做的就是添加隐藏输入来识别点击的来源。也像我在下面所做的那样从 url_for 中删除前导斜杠

<div class="col">
<div class="form-group">
<label>Enter Customer ID or leave blank for random selection </label>

<form method="POST" action={{url_for('suggestion')}}>
<input name="text", id='text', placeholder="Client ID" >
<input type="hidden" name="btn_identifier" value="client_id_identifier" />
<input type="submit" >
</form>
<form method="POST" action={{url_for('suggestion')}}>
<input name="textid", id='text', placeholder="Textid1">
<input name="textid1", id='text', placeholder="textid2 ">
<input name="textid2", id='text', placeholder="Textid3">
<input type="hidden" name="btn_identifier" value="text_id_identifier" />
<input type="submit" value="Submit">
</form>

main.py

from flask import Flask
from flask import render_template, url_for, request, redirect
app = Flask(__name__)

@app.route('/suggestion', methods=['GET', 'POST'])
def with_suggestions():
if request.methods == 'POST':
if request.form['btn_identifier'] == 'client_id_btn':
try:
client_id=request.form['text']
except:
# I think this would go in the second elif statement
model_id=request.form['textid']
model_id1=request.form['textid1']
model_id2=request.form['textid2']
elif request.form['btn_identifer'] == 'text_id_btn':
# run some code to handle a click that was originated from the second button
return render_template('index.html')

if __name__ == '__main__':
app.run()

关于html - Flask 多个提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52007908/

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