Python Answers

How to call a Python Flask function on button click event?

Spread the love

To call a Python Flask function on button click event, we can navigate to the view when the button is clicked.

For instance, we write

<form action="/forward/" method="post">
  <button name="forwardBtn" type="submit">Forward</button>

to add a button that navigates to the URL for the /forward/ route when we click on the Forward button.

The form is subbmitted when we click on the button.

Then we define the /forward/ route with the move_forward function by writing

from flask import Flask, render_template, Response, request, redirect, url_for

app = Flask(__name__)

def index():
    return render_template("index.html")

@app.route("/forward/", methods=["POST"])
def move_forward():
    forward_message = "Moving Forward..."
    return render_template("index.html", forward_message=forward_message)

It calls render_template to render index.html with the forward_message variable set to "Moving Forward...".

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.