0
votes

I'm trying to validate four forms from an Ajax request. My problem is that only one form is validated (geometry_building_form). The others do not contain errors, only an empty dictionary.

Another problem I have is that the validate_on_submit method does not work, I have to use the validate method.

This is the Flask view.

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

This is the Ajax code.

    <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>
1

1 Answers

2
votes

FormFields are useful for editing child objects or enclosing multiple related forms on a page which are submitted and validated together. While subclassing forms captures most desired behaviours, sometimes for reusability or purpose of combining with FieldList, FormField makes sense. (Taken from Documentation)

With that in mind-- you may want to create a wrapping form that encloses your sub-forms:

from wtforms import FormField

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

The later when you're processing the request, form = BuildingForm() will allow you to do form.validate_on_sumbit() and it will validate and enclose the various subforms as expected.