WTForms的Ajax验证失败

3
我正在使用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') is not a string
示例JSON消息如下: list_id=2&csrf_token=IjA0NGJjNzU1Nzg3ODg1ZjhhODQ0YzE5ODMwYzkzZTBkNjEyMWQyYjIi.Du1lBg.nJJpKiNSV4pnCLsIfzUaqlsmscg&title=ff&expensetype_id=1&price=f&quantity=1&currency_id=2&city=GHanzhaou&country_id=5&date=2018-12-08
然后我从print(form.data)中获取以下数据:
{'list_id': '2', 'title': 'ff', 'expensetype_id': 1, 'price': None, 'quantity': 1, 'currency_id': 2, 'country_id': 5, 'city': 'GHanzhaou', 'date': datetime.date(2018, 12, 8), 'exceptional_cost': False, 'submit': False, 'csrf_token': 'IjA0NGJjNzU1Nzg3ODg1ZjhhODQ0YzE5ODMwYzkzZTBkNjEyMWQyYjIi.Du1lBg.nJJpKiNSV4pnCLsIfzUaqlsmscg'}
现在我已经针对其他非Ajax函数进行了测试,当数据不正确时它们似乎也会出现'None'(例如,使用其他DecimalFields)。 在验证时,它们只返回“DataRequired”错误,页面处理显示。
我不太明白这个失败的原因。 非常感谢您的帮助和见解。
1个回答

2

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()]})

就是这样!非常感谢,我一直在盯着它看得眼花缭乱!我一直在看验证部分... - CWeasel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接