Flask select which form to POST by button click

# Import necessary modules
from flask import Flask, render_template, request

# Create a Flask application
app = Flask(__name__)

# Define routes and methods for the application
@app.route('/', methods=['GET', 'POST'])
def index():
    # Handle POST request
    if request.method == 'POST':
        # Check which button was clicked
        if 'form1_button' in request.form:
            # Process Form 1 data
            # Replace the following line with your Form 1 processing logic
            result = "Form 1 submitted"
        elif 'form2_button' in request.form:
            # Process Form 2 data
            # Replace the following line with your Form 2 processing logic
            result = "Form 2 submitted"
        else:
            # Handle other cases if needed
            result = "Unknown form submitted"

        # Render the result template with the processed result
        return render_template('result.html', result=result)

    # Render the initial template with buttons for each form
    return render_template('index.html')

# Run the application
if __name__ == '__main__':
    app.run(debug=True)

Create two HTML templates in the "templates" folder:

  1. index.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Form Selection</title>
</head>
<body>
    <h1>Select a Form</h1>
    <form method="post">
        <button type="submit" name="form1_button">Form 1</button>
        <button type="submit" name="form2_button">Form 2</button>
    </form>
</body>
</html>
  1. result.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Submission Result</title>
</head>
<body>
    <h1>Form Submission Result</h1>
    <p>{{ result }}</p>
</body>
</html>