我正在尝试从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>
答案 0 :(得分:1)
FormFields
对于编辑子对象或将多个相关表单封装在一起提交和验证的页面非常有用。虽然子类化表单捕获了大多数期望的行为,但有时为了重用性或与FieldList
结合的目的,FormField
是有意义的。 (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()
,它将按预期验证并附上各种子表单。