Flask Python Buttons

dojogeorge picture dojogeorge · Nov 5, 2013 · Viewed 159.8k times · Source

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

Miguel picture Miguel · Nov 5, 2013

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)