I'm trying to create two buttons on a page. Each one I would like to carry out a different Python script on the server. So far I have only managed to get/collect one button using.
def contact(): form = ContactForm() if request.method == 'POST': return 'Form posted.' elif request.method == 'GET': return render_template('contact.html', form=form)
What would I need to change based on button pressed?
In the Flask code you can add an action under every if statement of the corresponding button like rendering a template or running a python script. In the HTML code you can add as many buttons as you want just be sure to add the right values and names.
Give your two buttons the same name and different values:
<input type="submit" name="submit_button" value="Do Something"> <input type="submit" name="submit_button" value="Do Something Else">
Then in your Flask view function you can tell which button was used to submit the form:
def contact(): if request.method == 'POST': if request.form['submit_button'] == 'Do Something': pass # do something elif request.form['submit_button'] == 'Do Something Else': pass # do something else else: pass # unknown elif request.method == 'GET': return render_template('contact.html', form=form)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With