【发布时间】:2018-05-29 02:12:08
【问题描述】:
我正在将 Stripe 支付处理集成到我的 Django 应用程序中,但我无法找出“正确”的方式来验证客户的卡信息并在我的用户表中插入一行,其中包含用户的 Stripe 客户 ID。
理想情况下,我希望按照以下方式做一些事情,其中我的 CheckoutForm 验证卡详细信息并在它们不正确时引发表单 ValidationError。但是,使用此解决方案,我无法找到一种方法来获取由 clean() 函数生成的 customer.id。
forms.py
class CheckoutForm(forms.Form):
email = forms.EmailField(label='E-mail address', max_length=128, widget=forms.EmailInput(attrs={'class': 'form-control'}))
stripe_token = forms.CharField(label='Stripe token', widget=forms.HiddenInput)
def clean(self):
cleaned_data = super().clean()
stripe_token = cleaned_data.get('stripe_token')
email = cleaned_data.get('email')
try:
customer = stripe.Customer.create(
email=email,
source=stripe_token,
)
// I can now get a customer.id from this 'customer' variable, which I want to insert into my database
except:
raise forms.ValidationError("It looks like your card details are incorrect!")
views.py
# If the form is valid...
if form.is_valid():
# Create a new user
user = get_user_model().objects.create_user(email=form.cleaned_data['email'], stripe_customer_id=<<<I want the customer.id generated in my form's clean() method to go here>>>)
user.save()
我能想到的唯一其他解决方案是在表单验证后在views.py 中运行stripe.Customer.create() 函数。这行得通,但它似乎不是编码事物的“正确”方式,因为据我了解,表单字段的所有验证都应该在 forms.py 中完成。
在这种情况下,正确的 Django 编码实践是什么?我应该将我的卡验证代码移动到views.py,还是有一种更简洁的方法将卡验证代码保留在forms.py 中并从中取出customer.id?
【问题讨论】:
标签: django forms validation django-forms stripe-payments