8

クレジット カード情報を収集する登録フォームがあります。ワークフローは次のとおりです。

  • ユーザーは、ストライプを通じて登録データとカード データを入力します。
  • フォームの登録データが検証されます。
  • フォームが有効な場合、支払いが処理されます。
  • 決済が通ればOK、ユーザー登録完了です。
  • 支払いが失敗した場合、フォームの非表示フィールドで検証エラーを発生できるようにしたいと考えています。それは可能ですか?

フォーム送信コードは次のとおりです。

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

2 に答える 2

26

必要なフィールドにエラーを手動で追加することで解決しました。

そのように見えます

try:

    [...]
except StripeError as e:
    form.payment.errors.append('the error message')
else:
    db.session.commit()
    return redirect(url_for('home'))
于 2013-11-07T11:27:29.073 に答える
3

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")
于 2014-06-02T14:48:46.897 に答える