首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Flask -在Ajax请求上验证几个表单

Flask -在Ajax请求上验证几个表单
EN

Stack Overflow用户
提问于 2018-02-14 19:15:08
回答 1查看 624关注 0票数 0

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

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

这是Flask视图。

代码语言:javascript
复制
@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代码。

代码语言:javascript
复制
    <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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-15 05:14:46

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

考虑到这一点--您可能希望创建一个包含子窗体的包装窗体:

代码语言:javascript
复制
from wtforms import FormField

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

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48785840

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档