问题描述
我是不熟悉烧瓶的人,尝试建立一个简单的人口统计调查.验证 StringField
(例如国籍)可以正常工作时, RadioField
遇到了麻烦.如果我没有为 RadioField
提供任何输入,则不会出现错误消息.我认为问题出在我的jinja2模板中,但我找不到我做错的事情.
I'm new to flask and try to build a simple demographics survey. While validating a StringField
(e.g. Nationality) works fine, I have trouble with the RadioField
. No error messages occur if I don't provide any input for the RadioField
. I think the problem lies in my jinja2 template but I'm not able to find what I'm doing wrong.
有什么建议吗?
从main.py中提取:
extract from main.py:
class DemographicsForm(FlaskForm):
Gender = RadioField(
'Gender',
choices=[('M', 'Male'), ('F', 'Female'), ('O', 'Other')],
validators=[InputRequired()]
)
@app.route("/demographics", methods=['GET', 'POST'])
def demographics():
form = DemographicsForm()
return render_template('demographics.html', title='Demographic Information', form=form)
从demographics.html中提取:
extract from demographics.html:
<div class="form-group">
{{ form.Gender.label(class='radio') }}
{% if form.Gender.errors %}
{{ form.Gender(class='radio is-invalid') }}
<div class="invalid-feedback">
{% for error in form.Gender.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.Gender(class='radio') }}
{% endif %}
</div>
推荐答案
实际上,问题出在您的Jinja代码中.您实施错误处理的方式非常令人困惑.它应该像这样简单:
Actually the problem comes from your Jinja code. The way you implemented error handling is pretty confusing. It should be as simple as this one:
<div class="form-group">
{{ form.Gender.label(class='radio') }}
{{ form.Gender(class='radio') }}
{% for error in form.Gender.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</div>
因此,当您在未选择单选按钮的情况下发送表单时,错误消息将出现在页面上(在上面的代码中将显示为红色)和控制台中.
Thus, when you send the form without having selected a radio button, an error message will appear on your page (in the code above it will appear in red) and in your console.
这篇关于RadioField永远不会正确验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!