dojogeorge dojogeorge - 6 months ago 30
Python Question

Flask Python Buttons

Im 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?

Answer

Give your two buttons the same name and different values:

<input type="submit" name="submit" value="Do Something">
<input type="submit" name="submit" 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'] == 'Do Something':
            pass # do something
        elif request.form['submit'] == 'Do Something Else':
            pass # do something else
        else:
            pass # unknown
    elif request.method == 'GET':
        return render_template('contact.html', form=form)