【发布时间】:2020-04-30 03:18:40
【问题描述】:
我有两个烧瓶形式的单选按钮。如果第一个单选按钮被选中“是”,我需要第二个单选按钮成为强制用户填写。我知道在 javascript 中有一些方法可以做到这一点,但我想将所有东西都包含在烧瓶 wtform 中,因为这是我主要做的事情,而且我是 javascript 新手。
在查看了之前的 stackoverflow 问题后,我找到了以下可能的解决方案,但这对我没有任何帮助。当我使用以下解决方案运行代码时,两个单选按钮都是必需的。如果第一个仅选中“是”,我希望第二个是强制性的。
class RequiredIf(InputRequired):
field_flags = ('requiredif',)
def __init__(self, other_field_name, message=None, *args, **kwargs):
self.other_field_name = other_field_name
self.message = message
def __call__(self, form, field):
other_field = form[self.other_field_name]
if other_field is None:
raise Exception('no field named "%s" in form' % self.other_field_name)
if bool(other_field.data):
super(RequiredIf, self).__call__(form, field)
else:
Optional().__call__(form, field)
class CheckInForm(FlaskForm):
question1= RadioField('Question1 Label', choices=[('Yes', 'Yes'), ('No', 'No')], validators=[DataRequired()])
question2 = RadioField('Question2 Label', choices=[('Yes', 'Yes'), ('No', 'No')], validators=[RequiredIf('question1')])
submit = SubmitField('Submit Form', render_kw={"class": "btn btn-primary btn-block"})
以下是我的html文件:
{% extends "base.html" %}
{% import 'wtf.html' as wtf %}
<body>
{% block app_content %}
{% block content %}
<h1><center>Check In</center></h1>
<form action="" method="post" novalidate>
{{ form.hidden_tag() }}
<h5> {{ form.question1.label }}</h5>
{% for subfield in form.question1%}
<tr> 
<td>{{ subfield }}</td>
<td>{{ subfield.label }}</td>  
</tr>
{% endfor %}
{% for error in form.question1.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
<h5> {{ form.question2.label }}</h5>
{% for subfield in form.question2%}
<tr> 
<td>{{ subfield }}</td>
<td>{{ subfield.label }}</td>  
</tr>
{% endfor %}
{% for error in form.question2.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</form>
{% endblock %}
{% endblock %}
【问题讨论】:
标签: python flask flask-wtforms