提交表单后,Flask-WTF动态无线电场正在运行新查询

时间:2018-06-26 17:04:49

标签: python sqlalchemy flask-wtforms

我正在使用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的新手,还没有达到我的编码要求。谢谢。

0 个答案:

没有答案
相关问题