0

I have a form around a table and in the table one of the columns has a checkbox for each row.

Item    Amount    Select
-------------------------
apple   10        [x]
banana  5         [ ]
orange  23        [ ]

I then have two buttons, one deletes the row, the other does something else in the backend with the same information.

<form action="{{ url_for('do_action') }}" method="post">
    <table>
    ...content
        <input name="check" type="checkbox">
    </table
<button type='submit'>Delete Row</button>
<button type='submit'>Update</button>
</form>

Is there a way to attach some sort of context to the form depending on the button I press?

I want my route in the backend to know what to do

@app.route('/do_action', methods=['POST'])
def do_action():
    if button.clicked == 'delete':
        # do delete action
    elif button.clicked == 'update':
        # do update action

    return 'Complete'
Ari
  • 5,301
  • 8
  • 46
  • 120
  • Possible duplicate of [Flask Python Buttons](https://stackoverflow.com/questions/19794695/flask-python-buttons) – metatoaster May 02 '19 at 00:43

1 Answers1

2

You can use <input> elements with the same name, but with different value attributes.

 <input type ="submit" name="submit" value="update">
 <input type ="submit" name="submit" value="delete">

On the backend, import the request object and deploy it conditionality:

from flask import request

if request.form.post['submit'] == 'update':
    ...
elif request.form.post['submit'] == 'delete':
    ...
else
    ...
Gabe
  • 956
  • 7
  • 8
  • This gave me an error, but `if request.form['submit']` worked. This statement was nested under `if form.validate_on_submit():`, not sure if that changes something in my case? I'm not well versed in routes. – dannypernik Sep 04 '21 at 03:34