首页 > 解决方案 > Flask-WTF Dynamic radiofield 在表单提交时运行新查询

问题描述

我正在使用 Flask-WTF 和 SQLAlchemy 构建一个多项选择测验,从数据库表中提取随机引号和可能的答案。我已经能够做到这一点。但是,当提交表单并将选择的答案保存到新的数据库表中时,我看到实际问题(引用)和答案已更改。看起来好像在提交表单时正在运行一个新查询。这是我的意思的一个简单示例。

带有选项的测验的实际问题

谁说……“天是蓝的。”

  1. 弗兰克(选作答案)
  2. 哈利
  3. 安妮
  4. 玛丽

保存到数据库的数据

问题:谁说...“苹果是红色的。”

选择的答案:汤姆

我试图弄清楚如何阻止额外的查询发生,以便我可以保存用户实际看到和回答的问题中的数据。

这是我的表格:

    class Quiz(FlaskForm):
        q1 = RadioField('', coerce=str, validators=[DataRequired()], choices=[])
        q2 = RadioField('', coerce=str, validators=[DataRequired()], choices=[])
        q3 = RadioField('', coerce=str, validators=[DataRequired()], choices=[])
        q4 = RadioField('', coerce=str, validators=[DataRequired()], choices=[])
        q5 = RadioField('', coerce=str, validators=[DataRequired()], choices=[])

而我的查看路线:

    @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 = [("1", answer), ("2", option_two), ("3", option_three), ("4", option_four)]
        if form.validate_on_submit():
            for field in form:
                if field.type == "CSRFTokenField":
                    continue
                else:
                    user_answer = field.data
                    question_id = field.id
                    question_line = field.label
                    correct_answer = answer
                    submission = Responses(question_id, question_line, user_answer, correct_answer)
                    db.session.add(submission)
                    db.session.commit()
            return redirect(url_for('you_passed'))
        return render_template('quiz.html', form=form)

任何帮助,将不胜感激。我也愿意接受有关我当前代码的任何建议。我是 Python 新手,我的编码还没有达到优雅的程度。谢谢。

标签: pythonsqlalchemyflask-wtforms

解决方案


推荐阅读