这是此逻辑的示例实现,可与 WTForms 本机功能一起使用。这里的技巧是,如果你想使用 WTForms 验证,你需要用每个可能的值来实例化表单,然后修改 Javascript 中的可用选项以显示基于其他选择的过滤值。
对于这个例子,我将使用州和县的概念(我使用大量地理数据,所以这是我构建的一个常见实现)。
这是我的表单,我为重要元素分配了唯一 ID,以便从 Javascript 访问它们:
class PickCounty(Form):
form_name = HiddenField('Form Name')
state = SelectField('State:', validators=[DataRequired()], id='select_state')
county = SelectField('County:', validators=[DataRequired()], id='select_county')
submit = SubmitField('Select County!')
现在,要实例化和处理表单的 Flask 视图:
@app.route('/pick_county/', methods=['GET', 'POST'])
def pick_county():
form = PickCounty(form_name='PickCounty')
form.state.choices = [(row.ID, row.Name) for row in State.query.all()]
form.county.choices = [(row.ID, row.Name) for row in County.query.all()]
if request.method == 'GET':
return render_template('pick_county.html', form=form)
if form.validate_on_submit() and request.form['form_name'] == 'PickCounty':
# code to process form
flash('state: %s, county: %s' % (form.state.data, form.county.data))
return redirect(url_for('pick_county'))
响应县的 XHR 请求的 Flask 视图:
@app.route('/_get_counties/')
def _get_counties():
state = request.args.get('state', '01', type=str)
counties = [(row.ID, row.Name) for row in County.query.filter_by(state=state).all()]
return jsonify(counties)
最后,放置在 Jinja 模板底部的 Javascript。我假设因为您提到了 Bootstrap,所以您使用的是 jQuery。我还假设这是在 javascript 中,所以我使用 Jinja 返回端点的正确 URL。
<script charset="utf-8" type="text/javascript">
$(function() {
// jQuery selection for the 2 select boxes
var dropdown = {
state: $('#select_state'),
county: $('#select_county')
};
// call to update on load
updateCounties();
// function to call XHR and update county dropdown
function updateCounties() {
var send = {
state: dropdown.state.val()
};
dropdown.county.attr('disabled', 'disabled');
dropdown.county.empty();
$.getJSON("{{ url_for('_get_counties') }}", send, function(data) {
data.forEach(function(item) {
dropdown.county.append(
$('<option>', {
value: item[0],
text: item[1]
})
);
});
dropdown.county.removeAttr('disabled');
});
}
// event listener to state dropdown change
dropdown.state.on('change', function() {
updateCounties();
});
});
</script>