栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用从先前字段中选择的值填充WTForms选择字段

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用从先前字段中选择的值填充WTForms选择字段

这是与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':        # pre to process form        flash('state: %s, county: %s' % (form.state.data, form.county.data))    return redirect(url_for('pick_county'))

Flask视图以响应对县的XHR请求:

@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)

最后,将Javascript放在Jinja模板的底部。我假设因为您提到了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>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/393918.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号