I have a registration form that collects credit card info. The workflow is as follows:
Here's a the form submission code:
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)
I solved it by manually appending errors to the field i wanted.
It looks like that
try:
[...]
except StripeError as e:
form.payment.errors.append('the error message')
else:
db.session.commit()
return redirect(url_for('home'))
on your wtform itself you can add a method prefixed with validate_
in order to raise an exception.
class RegistrationForm(Form):
amount = IntegerField('amount', validators=[Required()])
validate_unique_name(self, field):
if field.data > 10000:
raise ValidationError('too much money')
in my case I used it like so to validate that a user was not in the database already:
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With