【问题标题】:Display selected form items in another page with Flask使用 Flask 在另一个页面中显示选定的表单项
【发布时间】:2017-06-22 03:50:13
【问题描述】:

我正在使用 Flask 0.12 和 Python 3.6 创建一个简单的应用程序,当单击提交按钮时,它将在另一个页面中显示所选项目。

主要的 Flask 应用程序位于 app.py 中:

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')

这会使用 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>

当点击提交按钮时,如何让 Flask 在我的results.html 模板中显示所选项目?

【问题讨论】:

    标签: python html twitter-bootstrap-3 flask


    【解决方案1】:

    您必须对表单进行一些更改才能显示在结果页面中。

    1. 您必须在表单中添加操作 url 和方法

      <form action="/result" method="post">
      
    2. 在选择字段中添加名称

      <select id="vehicle" class="form-control" name="vehicle">
      <select id="year" class="form-control" name="year">
      
    3. 使用flask请求获取表单值

      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. 最后在你的结果 html 页面中添加这些...

      {{ vehicle }} {{ year }}
      

    【讨论】:

    • 在第4步中,应该是{{ year }}而不是{{ result }}
    • 在您的回答中修复了第 4 步,这似乎可行,谢谢
    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    相关资源
    最近更新 更多