【问题标题】:Getting checkbox form data when the form is generated by Jinja2Jinja2生成表单时获取复选框表单数据
【发布时间】:2021-06-11 22:59:02
【问题描述】:

我正在尝试制作一个测验网站。我有一个表单,用户可以一次选择多个复选框。我正在使用 Flask 的 Jinja2 模板来创建复选框。每个部分的问题数量可能会发生变化。这是问题页面的代码。用户选择一些复选框并将它们提交给服务器。由于多个问题共享相同的名称,我如何知道选中了哪个复选框?有没有更好的方法来解决这个问题?

{% block head %}
<title>Questions Page</title>
{% endblock %}

{% block body %}
<div class="container-fluid">
    <h1>{{title}}</h1>
    {% for question in rel%}
    <form action="/questions" method="POST">
        <div class="form-check">
            <input class="form-check-input" type="checkbox" value="" id="defaultCheck1" name="check1">
            <label class="form-check-label" for="defaultCheck1">
            {{question}}
        </div>
        {% endfor %}
        <button class="btn btn-success" type="submit">
            Submit
        </button>
    </form>
</div>
{% endblock %}

Python 代码: 我正在使用列表来存储问题集标题和问题列表。 #hen 首次加载,/questions 将显示标题为“A”,复选框显示为“A1”、“A2”、“A3”、“A4”。提交表单后,/questions 将显示标题为“B”,复选框显示为“B1”,依此类推,直到问题列表为空。我是否可以获取检查了哪些问题的列表,例如["A1", "A2"]

from flask import Flask, render_template,request

app = Flask(__name__)

title = ["A","B"]
rel = [["A1", "A2","A3","A4"], ["B1","B2","B3"]]

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

@app.route("/questions", methods = ['GET','POST'])
def questions():
    if request.method == "GET":
      return render_template('questions.html', rel=rel.pop(0), title=title.pop(0))
    elif request.method == "POST":
       #???
       return str(request.form.getlist('check1')) #This returns a list like [","]
       
app.run(debug=True) 

【问题讨论】:

  • 是同一页的问题还是一页的一个问题。
  • 都是一页。

标签: python http flask http-post jinja2


【解决方案1】:

我想通了。我只需将{{question}} 添加到复选框的值中,然后我就得到了带有它们的值的复选框列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多