首页 > 解决方案 > WTForms Ajax 验证失败

问题描述

我正在用 Python 构建我的第一个 Web 应用程序,并使应用程序更加动态。

只要用户填写正确的数据,代码就可以正常工作。但是我现在正在测试一些错误的输入,并且它失败了。我正在使用 WTForms 并且在构建非 ajax 页面时一切正常,当用户在其中输入错误数据时,应用程序给前端一个很好的“无效输入”。现在应用程序中断。

这是表格:

class ExpenseForm(FlaskForm):
    list_id = HiddenField(validators=[DataRequired()])
    title = StringField('Expense', validators=[DataRequired()])
    expensetype_id = SelectField('Expense Type', coerce=int)
    price = DecimalField('Cost', places=2, validators=[DataRequired()])
    quantity = IntegerField('Quantity', validators=[DataRequired()])
    currency_id = SelectField('Currency', coerce=int)
    country_id = SelectField('Country', coerce=int)
    city = StringField('City', validators=[DataRequired()])
    date = DateField('Date', validators=[DataRequired()])
    exceptional_cost = BooleanField('Exceptional cost')
    submit = SubmitField('Add')

我的路线:

@bp.route('/commit_expense', methods=['POST'])
@login_required
def commit_expense():
    form = ExpenseForm()
    form.expensetype_id.choices = [(et.id, et.name) for et in Expensetype.query.order_by('name')]
    form.currency_id.choices = [(c.id, c.short) for c in Currency.query.order_by('short')]
    form.country_id.choices = [(co.id, co.name) for co in Country.query.order_by('name')]
    print(form.data)
    if form.validate_on_submit():
        extra_add_expense(form)
        return jsonify({'success': 'Expense added'})
    return jsonify({'error':'Failed to add expense',
                        'form_errors':[{form[field].label: ', '.join(errors)} for field, errors in form.errors.items()]})

和javascript:

$(function () {
    $("#expense_form").submit(function (event) {
        event.preventDefault(); // Prevent the form from submitting via the browser
        var form = $(this);
        var error_div = $("#form_errors");
        $(error_div).children().remove();
        $.ajax({
            type: form.attr('method'),
            url: form.attr('action'),
            data: form.serialize()
        }).done(function (data) {
            if (data.error) {
                for (item in data.form_errors) {
                    Object.keys(data.form_errors[item]).forEach(function (key) {
                        $('<p>').text(key + ': ' + data.form_errors[item][key]).addClass("show_error").appendTo(error_div);
                    });
                };
            } else {
                form[0].reset();
                daily_refresh();
            }
        }).fail(function (data) {
            // Finish fail here
        });
    });
});

因此,只要我在所有字段中填写正确的信息,一切都会顺利通过,但是当我填写一些错误的信息时,例如价格,我得到了这个:

TypeError: key Label('price', 'Cost') 不是字符串

示例 json 消息是:

list_id=2&csrf_token=IjA0NGJjNzU1Nzg3ODg1ZjhhODQ0YzE5ODMwYzkzZTBkNjEyMWQyYjIi.Du1lBg.nJJpKiNSV4pnCLsIfzUaqlsmscg&title=ff&expensetype_id=1&price=f&quantity=1¤cy_12-id=2&city=country=1¤cy_id=2&city=GHanzha

然后我从 print(form.data) 中得到以下数据:

{'list_id':'2','title':'ff','expensetype_id':1,'price':无,'quantity':1,'currency_id':2,'country_id':5,'city' : 'GHanzhaou', 'date': datetime.date(2018, 12, 8), 'exceptional_cost': False, 'submit': False, 'csrf_token': 'IjA0NGJjNzU1Nzg3ODg1ZjhhODQ0YzE5ODMwYzkzZTBkNjEyMWQyYjIi.Du1lpnCLs.nIfJ

现在我已经针对我的其他非 ajax 函数对此进行了测试,当数据不正确时它们似乎也有一个“无”(例如使用其他 DecimalFields)。在验证时,它们只返回“DataRequired”错误,页面处理显示。

我不太明白这次失败背后的原因。非常感谢任何帮助或见解。

提前致谢!

标签: javascriptpythonajaxwtforms

解决方案


form[field].label是一个Label实例,而不是字符串。

用于form[field].label.text获取标签的字符串表示形式。

您视图的最后一行应该是

 return jsonify({'error':'Failed to add expense',
                 'form_errors':[{form[field].label.text: ', '.join(errors)} for field, errors in form.errors.items()]})

推荐阅读