Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display selected form items in another page with Flask

I'm using Flask 0.12 with Python 3.6 to create a simple app that will display selected items in another page when the submit button is clicked.

The main Flask app is in app.py as:

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/result', methods=['POST'])
def result():
    return render_template('result.html')

This renders the following webpage using Bootstrap:

<h1>Example Page</h1>

<p>Choose the options in the form below then submit your selections.</p>

<form action="">
  <div class="form-group">
    <label for="vehicle">Vehicle</label>
    <select id="vehicle" class="form-control">
      <option>truck</option>
      <option>car</option>
      <option>van</option>
    </select>
  </div>

  <div class="form-group">
    <label for="year">Year</label>
    <select id="year" class="form-control">
      <option>1972</option>
      <option>1999</option>
      <option>2010</option>
    </select>
  </div>
</form>

<br>

<button type="submit" class="btn btn-default">Submit</button>

How can I get Flask to show the selected items in my results.html template when the submit button is clicked?

like image 360
wigging Avatar asked Nov 25 '25 07:11

wigging


1 Answers

You have to make few changes in the form to display in result page.

  1. You have to add action url and method in form

    <form action="/result" method="post">
    
  2. Add name in the select field

    <select id="vehicle" class="form-control" name="vehicle">
    <select id="year" class="form-control" name="year">
    
  3. Use flask request to get the form values

    from flask import request
    
    # inside your POST view
    vehicle = request.form.get('vehicle')
    year = request.form.get('year')
    return render_template('result.html', vehicle=vehicle, year=year)
    
  4. Finally in your result html page add these...

    {{ vehicle }} {{ year }}
    
like image 127
Raja Simon Avatar answered Nov 26 '25 22:11

Raja Simon



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!