How do I in Flask get what of two buttons in same form has been clicked to perform different actions?

Viewed 1067

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>
1 Answers

HTML Change:

You can have a form, with one text box and two buttons. The button names are the same(two_buttons) and will have different values(add-update and remove, which will be used in the flask to identify them.

two_button_add_and_remove.html

<form action="{{ url_for('check_button')}}" method="POST">
        <!-- 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 name="two_buttons" value="add-update" id="add-update" type="submit" class="btn btn-primary mb-2 mr-2">Add/Update</button>
    <!-- Remove button -->
    <button name="two_buttons" value="remove" id="remove" type="submit" class="btn btn-primary mb-2">Remove</button>
</form>

Now in Flask, check the value of request.form['two_buttons'] and based on it call your add or remove function with parameter request.form['search']

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


@app.route('/check_button', methods=['GET','POST'])
def check_button():
    print("Request.method:", request.method)
    try:
        if request.form['two_buttons'] == "add-update": # check if value is "add-update"
            print(f"call add-update_function with {request.form['search']}")
        else:
            print(f"call remove_function with {request.form['search']}")
        return render_template('two_button_add_and_remove.html')
    except Exception as e:
        return render_template('two_button_add_and_remove.html')

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

Related