Chris van den Berg Chris van den Berg - 3 years ago 227
Python Question

How Handle a button click on python/Flask

I'm building an small application and want to handle a button click using Flask. What do i need to add to get it working>

If you have the following in the template:

<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>

<div class="container">
<h2>Button Pressed: {{ButtonPressed}} </h2>
<input type="submit" value="Click Me" >
</div>

</body>




And the following in
.py


Button Pressed = 0
@app.route('/button', methods=["GET", "POST"])
def button():
if request.method == "GET":
return render_template("button.html", ButtonPressed = ButtonPressed)
return redirect(url_for('button'))


I search a lot, but all of it is in like a form. But this should not be in a form right?

Thanks in advance!

Answer Source

It should be within a form for it to be submitted.

Method-1:

`<div class="container">
    <h2>Button Pressed: {{ButtonPressed}}</h2>
    <form method="post">
        <input type="submit" value="Click Me" >
    </form>
 </div>`

Python -

ButtonPressed = 0        
@app.route('/button', methods=["GET", "POST"])
def button():
    if request.method == "POST":
        return render_template("button.html", ButtonPressed = ButtonPressed)
        # I think you want to increment, that case ButtonPressed will be plus 1.
    return render_template("button.html", ButtonPressed = ButtonPressed)

Method 2 -

Use Ajax to submit form. Read the documentation here http://api.jquery.com/jquery.ajax/

Submit a post request and your Flask application will send ButtonPressed incremented value to the function, and you can process value however you want. Still, you need a form for this and you need to update ButtonPressed value using JavaScript. However, ButtonPressed value should be maintained in some database if you need it to be stored.

Method 3 -

Without a form, you can make link look like button using Bootstrap and update it directly on UI in case you don't need the ButtonPressed value stored somewhere which will also avoid unnecessary call to server (you don't want to store it). Bootstrap - http://getbootstrap.com/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download