python - 使用 Flask 在另一个页面中显示选定的表单项

标签 python html twitter-bootstrap-3 flask

我正在使用 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 模板中显示所选项目?

最佳答案

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

  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 }}
    

关于python - 使用 Flask 在另一个页面中显示选定的表单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44689801/

相关文章:

iphone - 如何使面包屑具有响应性?

python - Flask jsonify - 如何发回字符串?

html - 使用 Golang/Gin 后端发布 HTML 表单

twitter-bootstrap - 使用 Bootstrap 将列更改为行布局

javascript - Angular 2使用onchange创建html元素

java - 在 XSLT 中使用 spring 标签

jquery - 多个元素与折叠的全宽按钮内联(Bootstrap)

python - 在 Django 应该传递的时候测试不传递

python - 使用 Pyplot 绘制平滑曲面

Python从列表中提取第一个元素并清理字符串