【问题标题】:Flask - Validate several forms on Ajax requestFlask - 验证 Ajax 请求的几个表单
【发布时间】:2018-02-14 11:15:08
【问题描述】:

我正在尝试验证来自 Ajax 请求的四个表单。我的问题是只验证了一种形式(geometry_building_form)。其他的不包含错误,只有一个空字典。

我遇到的另一个问题是validate_on_submit方法不起作用,我必须使用validate方法。

这是 Flask 视图。

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def building():
    building_parameters_form = BuildingParametersForm()
    building_geometry_form = BuildingGeometryForm()
    wind_form = WindForm()
    topography_form = TopographyForm()
    if request.method == 'POST':
        if building_geometry_form.validate() and building_parameters_form.validate() and wind_form.validate() and topography_form.validate():
            return redirect('/index')
        else:
            return jsonify(data=wind_form.errors) #Testing the wind form
    return render_template('wind/building.html', bp_form=building_parameters_form,
                            bg_form=building_geometry_form, w_form=wind_form, t_form=topography_form)

这是 Ajax 代码。

    <script>$(document).ready(function() {
        $("#button").click(function(event) {
            var csrf_token = "{{ csrf_token() }}";
            var url = "{{ url_for('building') }}";
            event.preventDefault();
            $.ajax({
                type: "POST",
                url: url,
                dataType: 'json',
                data: $('#geometry-form, #parameters-form, #wind-form, #topography-form').serialize(),
                success: function (data) {
                    console.log(data)
                }
        });
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrf_token)
                }
            }
        })
    });
});
</script>

【问题讨论】:

    标签: ajax flask flask-wtforms


    【解决方案1】:

    FormFields 可用于编辑子对象或在页面上包含多个相关表单,这些表单一起提交和验证。虽然子类化表单捕获了最需要的行为,但有时为了可重用性或与FieldListFormField 结合的目的是有意义的。 (Taken from Documentation)

    考虑到这一点 - 您可能想要创建一个包含子表单的包装表单:

    from wtforms import FormField
    
    class BuildingForm(Form):
        building = FormField(BuildingGeometryForm)
        wind = FormField(WindForm)
        topography = FormField(TopographyForm)
    

    稍后当您处理请求时,form = BuildingForm() 将允许您执行 form.validate_on_sumbit(),它将按预期验证并包含各种子表单。

    【讨论】:

    • 这听起来很有希望。在 Jinja 中渲染是同一个过程?
    • 差不多——但是因为它们是子表单(假设WindForm 上有一个description),你可以通过{{ form.wind.description }} 得到那个表单元素,所以他们真的是嵌套的,而不是只是组合的。
    • 我会试试的。如果有效,我会接受答案。谢谢!
    • 效果很好。我什至可以一起访问所有错误或按字段(表单)过滤它们。
    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2022-01-19
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    相关资源
    最近更新 更多