Use hasattr to check if a user already has a stripecustomer object

This commit is contained in:
M.Ravi 2017-10-26 15:00:54 +02:00
parent 8d2c120b43
commit ef9dc446db
2 changed files with 12 additions and 8 deletions

View file

@ -664,8 +664,12 @@ class PaymentVMView(LoginRequiredMixin, FormView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(PaymentVMView, self).get_context_data(**kwargs) context = super(PaymentVMView, self).get_context_data(**kwargs)
user = self.request.user user = self.request.user
if hasattr(user, 'stripecustomer'):
stripe_customer = user.stripecustomer
else:
stripe_customer = None
cards_list = UserCardDetail.get_all_cards_list( cards_list = UserCardDetail.get_all_cards_list(
stripe_customer= user.stripecustomer stripe_customer=stripe_customer
) )
context.update({ context.update({
'cards_list': cards_list, 'cards_list': cards_list,

View file

@ -221,19 +221,19 @@ class StripeCustomer(models.Model):
stripe_data = stripe_utils.create_customer(token, email, user.name) stripe_data = stripe_utils.create_customer(token, email, user.name)
if stripe_data.get('response_object'): if stripe_data.get('response_object'):
stripe_cus_id = stripe_data.get('response_object').get('id') stripe_cus_id = stripe_data.get('response_object').get('id')
if user.stripecustomer is None: if hasattr(user, 'stripecustomer'):
# The user never had an associated Stripe account
# So, create one
stripe_customer = StripeCustomer.objects.create(
user=user, stripe_id=stripe_cus_id
)
else:
# User already had a Stripe account and we are here # User already had a Stripe account and we are here
# because the account was deleted in dashboard # because the account was deleted in dashboard
# So, we simply update the stripe_id # So, we simply update the stripe_id
user.stripecustomer.stripe_id = stripe_cus_id user.stripecustomer.stripe_id = stripe_cus_id
user.stripecustomer.save() user.stripecustomer.save()
stripe_customer = user.stripecustomer stripe_customer = user.stripecustomer
else:
# The user never had an associated Stripe account
# So, create one
stripe_customer = StripeCustomer.objects.create(
user=user, stripe_id=stripe_cus_id
)
return stripe_customer return stripe_customer
else: else:
return None return None