我有一张收集信用卡信息的注册表。工作流程如下:
这是表单提交代码:
def register():
form = RegistrationForm()
if form.validate_on_submit():
user = User(
[...]
)
db.session.add(user)
#Charge
amount = 10000
customer = stripe.Customer.create(
email=job.company_email,
card=request.form['stripeToken']
)
try:
charge = stripe.Charge.create(
customer=customer.id,
amount=amount,
currency='usd',
description='Registration payment'
)
except StripeError as e:
***I want to raise a form validation error here if possible.***
db.session.commit()
return redirect(url_for('home'))
return render_template('register.html', form=form)
答案 0 :(得分:23)
我通过手动将错误添加到我想要的字段来解决它。
看起来像那样
try:
[...]
except StripeError as e:
form.payment.errors.append('the error message')
else:
db.session.commit()
return redirect(url_for('home'))
答案 1 :(得分:1)
在你的wtform上你可以添加一个前缀为validate_
的方法来引发异常。
class RegistrationForm(Form):
amount = IntegerField('amount', validators=[Required()])
validate_unique_name(self, field):
if field.data > 10000:
raise ValidationError('too much money')
就我而言,我这样使用它来验证用户是否已经不在数据库中了:
class Registration(Form):
email = StringField('Email', validators=[Required(), Email()]) # field for email
# ...
def validate_email(self, field): # here is where the magic is
if User.query.filter_by(email=field.data).first(): # check if in database
raise ValidationError("you're already registered")