python - Flask-WTF Dynamic radiofield 在表单提交时运行新查询
问题描述
我正在使用 Flask-WTF 和 SQLAlchemy 构建一个多项选择测验,从数据库表中提取随机引号和可能的答案。我已经能够做到这一点。但是,当提交表单并将选择的答案保存到新的数据库表中时,我看到实际问题(引用)和答案已更改。看起来好像在提交表单时正在运行一个新查询。这是我的意思的一个简单示例。
带有选项的测验的实际问题
谁说……“天是蓝的。”
- 弗兰克(选作答案)
- 哈利
- 安妮
- 玛丽
保存到数据库的数据
问题:谁说...“苹果是红色的。”
选择的答案:汤姆
我试图弄清楚如何阻止额外的查询发生,以便我可以保存用户实际看到和回答的问题中的数据。
这是我的表格:
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 新手,我的编码还没有达到优雅的程度。谢谢。
解决方案
推荐阅读
- swift - 无法在真机上安装“项目名称”
- java - 检查谁在使用 Thread.interrupted() 而没有抛出 InterruptedException 的好方法?
- hibernate - 我真的需要两次列出@Entity 吗?
- symfony - 使用 Symfony 3 进行路由翻译
- reactjs - Reactable 不能在生产模式下工作,但在开发模式下工作正常
- typescript - 你将如何获得 TypeScript 中某个类型的方法的名称?
- c# - 如何编写风格化但独立于操作系统的 WPF 控件。使用 Microsoft.Windows.Themes
- imagej - 调整宏 ImageJ 中的阈值
- asp.net-mvc - 传入字典的模型项是 *** 类型,但此字典需要 *** 类型的模型项
- php - 我缺少什么 php 概念?