I have a single input field where I wan't 2 buttons with different actions.
<!-- Search box -->
<input type="text" class="form-control mb-2 mr-sm-2" placeholder="UserID" name="search"
aria-describedby="useridHelp" required pattern="[0-9]{5,7}">
<!-- Submit/Update button -->
<button id="add-update" type="button" class="btn btn-primary mb-2 mr-2">Add/Update</button>
<!-- Remove button -->
<button id="remove" type="button" class="btn btn-primary mb-2">Remove</button>
If I make the "add-update" button to a type="submit" and use if request.method == 'POST': in Flask then I Submit the value of the field. Great.
But how do I call the "remove" button into Flask so I can give it a function?
In other words. When a user click the "Add/Update button" the field input should be added to my database. When a user click the "Remove" button the field input should be deleted from my database.
How do I grab which button has been clicked in Flask?
I found the solution here: https://predictivehacks.com/?all-tips=how-to-add-action-buttons-in-flask
The answer is to do:
if request.form.get('action1') == 'VALUE1':
The example is:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
if request.form.get('action1') == 'VALUE1':
pass # do something
elif request.form.get('action2') == 'VALUE2':
pass # do something else
else:
pass # unknown
elif request.method == 'GET':
return render_template('index.html', form=form)
return render_template("index.html")
<h3>Our Flask Buttons<h3/>
<form method="post" action="/">
<input type="submit" value="VALUE1" name="action1"/>
<input type="submit" value="VALUE2" name="action2" />
</form>