[python] Flask Python Buttons

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?

This question is related to python html button flask

The answer is


Apply (different) name attribute to both buttons like

<button name="one">

and catch them in request.data.


I handle it in the following way:

<html>
    <body>

        <form method="post" action="/">

                <input type="submit" value="Encrypt" name="Encrypt"/>
                <input type="submit" value="Decrypt" name="Decrypt" />

        </form>
    </body>
</html>
    

Python Code :

    from flask import Flask, render_template, request
    
    
    app = Flask(__name__)
    
    
    @app.route("/", methods=['GET', 'POST'])
    def index():
        print(request.method)
        if request.method == 'POST':
            if request.form.get('Encrypt') == 'Encrypt':
                # pass
                print("Encrypted")
            elif  request.form.get('Decrypt') == 'Decrypt':
                # pass # do something else
                print("Decrypted")
            else:
                # pass # unknown
                return render_template("index.html")
        elif request.method == 'GET':
            # return render_template("index.html")
            print("No Post Back Call")
        return render_template("index.html")
    
    
    if __name__ == '__main__':
        app.run()

I think this solution is good:

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()
    if form.validate_on_submit():
        if form.submit.data:
            pass
        elif form.submit2.data:
            pass
    return render_template('contact.html', form=form)

Form:

class ContactForm(FlaskForm):

    submit = SubmitField('Do this')
    submit2 = SubmitField('Do that')

In case anyone was still looking and came across this SO post like I did.

<input type="submit" name="open" value="Open">
<input type="submit" name="close" value="Close">

def contact():
    if "open" in request.form:
        pass
    elif "close" in request.form:
        pass
    return render_template('contact.html')

Simple, concise, and it works. Don't even need to instantiate a form object.


The appropriate way for doing this:

@app.route('/')
def index():
    if form.validate_on_submit():
        if 'download' in request.form:
            pass # do something
        elif 'watch' in request.form:
            pass # do something else

Put watch and download buttons into your template:

<input type="submit" name="download" value="Download">
<input type="submit" name="watch" value="Watch">

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to button

How do I disable a Button in Flutter? Enable/disable buttons with Angular Disable Button in Angular 2 Wrapping a react-router Link in an html button CSS change button style after click Circle button css How to put a link on a button with bootstrap? What is the hamburger menu icon called and the three vertical dots icon called? React onClick function fires on render Run php function on button click

Examples related to flask

Flask at first run: Do not use the development server in a production environment Flask - Calling python function on button OnClick event python-How to set global variables in Flask? In Flask, What is request.args and how is it used? How to print from Flask @app.route to python console What does "app.run(host='0.0.0.0') " mean in Flask Making an asynchronous task in Flask Flask ImportError: No Module Named Flask can you add HTTPS functionality to a python flask web server? How to get http headers in flask?