如果记入金额大于账户余额,wtforms 会引发 ValidationError

wtforms raise ValidationError if crediting amount is greater than account's balance

我有一个名为 Account 的 table,它有两种方法(投资和取款),我在取款方法上遇到了问题。如果入账金额大于账户余额,我想收到一条 ValidationError 消息。

这是我的试用版

def Withdraw(self):
        account = Accounts.query.filter_by(name=self.name).order_by(Account.id.desc()).first()
        if self.credit > account.balance:
            raise ValidationError('There is no enough balance in: '+ str(account.name)+ ' please try to Withdraw another account!')
        else:
            account_balance = float(float(account.balance) - float(self.credit))
            trans = Account(name=account.name, descrip=self.descrip, credit=self.credit,balance=account_balance)
            db.session.add(trans)
            db.session.commit()

我在代码下面得到了这个概念

def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user:
            raise ValidationError('This emaill is alrealy exist in our system please choose another email')

我希望这足以解释我的问题,请让我获得帮助 ):

Flask-WTForms 验证是一个特定的(子类)函数,在您验证表单时运行。

最好的办法是通过覆盖它来连接到表单验证函数:

class MyForm(FlaskForm):
    field1 = ..
    field2 = ..
    credit = ..

    def validate(self):
        """Overwrite the Base validation function"""
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        # now custom validation code:
        account = Accounts.query.filter_by(name=self.name).order_by(Account.id.desc()).first()
        if self.credit > account.balance:
            self.credit.errors.append('There is not enough balance...')
            return False

        return True

如果此 returns 为真,假设可以进行 credit/debit 操作,您可以自由地继续您的应用程序,否则会产生验证错误。

如果我是你,我会确保我的数据库 table 有一个约束来确保你不能提交错误的数据。数据库的完整性是更高的优先级,虽然 webform 验证很好,但不一定足以保持数据库的完整性。