![](/img/trans.png)
[英]validate_on_submit fails on POST when attributes of form fields modified in view function
[英]validate_on_submit() fails when RadioButton choices are dynamically generated
我正在创建类似测验的Web应用程序,以使用Flask,Jinja,WTForms,SqlAlchemy等学习语言。一旦用户通过成功浏览JSON文件中存储的所有级别来完成此类语言课程,我希望该应用程序为他提供一种练习模式,用户将回答随机选择的级别。
当我运行该应用程序时,我可以根据需要看到从随机级别的值生成的单选按钮,但是当我选择任何答案并提交时, form.validate_on_submit()返回False,而form.errors返回{'practiceform':[u '无效的选择']} 。 当我将值硬编码为currentLevel变量时,它可以正常工作。
views.py
@user_blueprint.route('/courses/<course>/quiz/practice',methods=['GET','POST'])
@login_required
def practice(course):
courseClass = class_for_name("project.models", course.capitalize())
courses = courseClass.query.filter_by(email=current_user.email).first()
maxLevel = courseClass.query.filter_by(email=current_user.email).first().get_maxLevel()
currentLevel = randint(0, maxLevel-1) # If this value is hard-coded or fetched from db, it works correctly
dic = generateQuestion(course, currentLevel)
display = dic["display"]
correct = dic["correct"]
options = dic["options"]
form = PracticeForm(request.form)
form.practiceform.choices = [(option, option) for option in options]
if form.validate_on_submit():
practiceForm = form.practiceform.data
if ((practiceForm == correct) and courses):
# Do something
flash("Nice job", 'success')
return redirect(url_for('user.practice', course=course))
else:
# Do something else
flash("Wrong answer", 'danger')
return redirect(url_for('user.practice', course=course))
return render_template('courses/practice.html', form=form, display=display)
表格
class PracticeForm(Form):
practiceform = RadioField('practice')
Practice.html
{% extends "_base.html" %}
{% block content %}
<form action='' method='POST' role='form'>
<p>
<!-- Tried put form.csrf, form.csrf_token, form.hidden_tag() here -->
{{ form.practiceform() }}
</p>
<input type="submit" value="submit" />
</form>
{% endblock %}
那我在那儿想念什么? 假设硬编码级别25正常工作,或者数字25是在randint中随机生成的,那又有什么区别呢?
我的猜测是option
是int
,错误WTForms从request.form
获取了str
。
当数据从请求返回时,WTForms会将其视为string
,除非您使用wtforms.fields.*Field
构造函数的coerce
kwarg显式指定类型:
practiceform = RadioField('practice', coerce=int)
因此,我发现randint()引起了问题,因为GET和POST动作都调用了procedure(course)方法,导致大多数情况下使用两个不同的整数->两种不同的形式。 所以我重构了代码。 保留了GET操作的Practice(course)方法,并创建了一个处理POST操作的新方法,从而解决了该问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.