小编典典

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

flask

对此不熟悉,尝试按照著名的Flask教程使用Flask-bootstrap,Flask-wtforms,Jinja等构建一个应用程序

我有一个带有2个选择字段和一个按钮的表单。

class Form(FlaskForm): 
    school_year = SelectField('School year', choices=some_tuples_list)
    category = SelectField('Category', choices=[]) 
    submit = SubmitField('submit')

我只希望第一个字段预先填充,而另一个字段根据前一个字段的选定值填充(在客户端?)。

在模板中,我尝试类似

{{ form.school_year(**{"onchange":"getCategories()"}) }}

可以正常工作(只要我返回元组列表以使用正确的javascript和路由填充下一个字段),但我想要以下内容

{{ wtf.form_field(form.school_year(**{"onchange":"getCategories()"})) }}

这不起作用(错误:wtforms.widgets.core.HTMLString对象没有属性“标志”)

因此,我想我的问题确实是:如何在该wtf表单字段上实现onChange事件?(这是我必须要做的,还是视图函数有办法吗?)

提前致谢。


阅读 806

收藏
2020-04-06

共1个答案

小编典典

这是与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'))

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>
2020-04-06