wtforms raise a validation error after the form is validated

applechief picture applechief · Nov 7, 2013 · Viewed 9.9k times · Source

I have a registration form that collects credit card info. The workflow is as follows:

  • User enters registration data and card data through stripe.
  • The form is validated for registration data.
  • If the form is valid, payment is processed.
  • If payment goes through, it's all good, the user is registered and moves on.
  • If the payment fails, i want to be able to raise a validation error on a hidden field of the form. Is that possible?

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)

Answer

applechief picture applechief · Nov 7, 2013

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'))