Python/Flask-WTF - 如何随机化动态 RadioField 中的选择?

Python/Flask-WTF - How can I randomize the choices from dynamic RadioField?

我希望使用 python/flask/flask-wtf 构建多项选择测验。我成功地能够从数据库中提取随机问题以及提取随机选择作为可能的答案。我在模板页面上使用 for 循环,首先显示问题,然后显示可能的答案。

这是我的模板。

<div class="quote-block">
{% for quote in quotes %}
    {{ quote.line_text }}
    <form method="POST">
        {{ form.hidden_tag() }}
        {{ form.question }}
        <input type="submit">
    </form>
{% endfor %}
</div>

我的问题是每个问题的可能答案都是相同的,并且顺序相同。我明白为什么会这样。对 RadioField 选择的数据库查询只发生一次。然后为 for 循环的每个实例提取该查询的结果。

这是我的观景路线。

@app.route('/quiz/', methods=['POST', 'GET'])
def quiz():
    quotes = Quotes.query.order_by(func.rand()).limit(5)
    form = Quiz()
    form.question.choices = [(choice.speaker_id, choice.speaker) for choice in Characters.query.order_by(func.rand()).limit(4)]
    return render_template('television/quiz.html', form=form, quotes=quotes, options=options)

还有我的表格。

class Quiz(FlaskForm):
    question = RadioField('Label', choices=[])

就像我说的,所有这些都有效。我只是不知道如何为每个问题开始一个新的选择查询。任何帮助将不胜感激。谢谢!

您可以尝试动态扩展 FlaskForm:

def Quiz(number_of_questions):
    class _Quiz(FlaskForm):
        pass
    for n in range(number_of_questions):
        setattr(_Quiz, RadioField('Label', choices=[]), 'question_' + str(n))
    return _Quiz()

现在您的表单中的每个问题都有一个 question_[n] 属性,因此您可以在 jijna2 中对其进行迭代:

<div class="quote-block">
<form method="POST">
{{ form.hidden_tag() }}
{% for q_num in range(n) %}
    {{ quotes[q_num].line_text }}
    {{ form['question_' + q_num|string }}
{% endfor %}
<input type="submit">
</form>
</div>

经过大量阅读和研究,我意识到我想做的太多太快了。所以我后退了一步,构建了我想要做的事情的块,然后它终于走到了一起。当然,我在表单验证部分遇到了新问题,但我会把它包括在一个新问题中。

我最大的障碍是我试图为 RadioField 随机选择选项。相反,我向数据库 table 添加了三列并在 table 中提供了选项。这使得通过一个查询提取选项和问题变得更加容易。

基本上,我是 运行 对表单中的字段进行 for 循环。如果该字段是 RadioField,它将对数据库运行查询并随机提取一行。然后我在拉出的行上使用另一个 for 循环并将不同的元素分配给 RadioField 的各个部分(标签,选择)。

如果您知道更优雅的方法,我很想听听。但目前它有效。

我的表单和模板保持不变。但这是我的新路线视图。

    @app.route('/quiz/', methods=['GET', 'POST'])
    def quiz():
        form = Quiz()
        for field in form:
            if field.type != "RadioField":
                continue
            else:
                pulls = Quotes.query.order_by(func.rand()).limit(1)
                for pull in pulls:
                    answer = pull.speaker
                    option_two = pull.option_two
                    option_three = pull.option_three
                    option_four = pull.option_four
                    question = pull.line_text
                    field.label = pull.line_text
                    field.choices = [(answer, answer), (option_two, option_two), (option_three, option_three), (option_four, option_four)]
            return redirect(url_for('you_passed'))
        return render_template('television/quiz.html', form=form)