简体   繁体   中英

How to get Flask app to interact with HTML options

I have the following variable: sentence_count = 2

and the following HTML template:

<div class="form-group">
          <h3>Length of summary (sentences):</h3>
          <select name="length">
            <option value="one">1</option>
            <option value="two">2</option>
            <option value="three">3</option>

          </select>
        </div>

This is my main flask route:

@app.route("/sum", methods=['POST'])
def sum():
    if request.method == 'POST':
        select = request.form.get('articles')
        if select == "Guardian":
            return redirect(url_for("guardian"))

        if select == "NYT":
            return redirect(url_for("nyt"))

I am already working with two different select forms, but I am unsure how to link a variable to the template. Ie so that when the option '3' is selected, the variable would change. What is the correct Jinja2 method of doing this?

<div class="form-group">
  <h3>Length of summary (sentences):</h3>
  <select name="length">
    <option value="two">1</option>
    <option value="two">2</option>
    <option value="two">3</option>

  </select>
</div>

If you submit this page, you can get the selected value from flask by request.args.get('length') . You have to use length keyword because that is the name you gave to the select tag. And you won't get the numbers, for example, if you select 3, you can't get the number 3 directly. Instead, it will return the option value attribute. So you have to change the HTML like this.

<div class="form-group">
  <h3>Length of summary (sentences):</h3>
  <select name="length">
    <option value="one">1</option>
    <option value="two">2</option>
    <option value="three">3</option>

  </select>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM