Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Handle a button click on python/Flask

Tags:

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!

like image 512
Chris van den Berg Avatar asked Oct 15 '25 15:10

Chris van den Berg


1 Answers

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/

like image 97
Mithun Mistry Avatar answered Oct 17 '25 05:10

Mithun Mistry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!