我试图呈现相同的页面“计费”,但根据用户是否有活动订阅而具有不同的变量。问题是当我尝试例外时,我得到 'NoneType' 对象没有属性 'DoesNotExist'。
如果成员资格为 False,我曾尝试使用:返回重定向但没有成功。
@login_required(login_url="/login")
def billing(request):
membership = False
cancel_at_period_end = False
user = request.user
pay = payment.objects.filter(user=user).last()
if request.method == 'POST':
stripe.api_key = settings.STRIPE_SECRET_KEY
#attempting cancelling subscription
subscription = stripe.Subscription.retrieve(pay.stripe_subscription_id)
subscription.cancel_at_period_end = True
pay.cancel_at_period_end = True
cancel_at_period_end = True
pay.paid = False
subscription.save()
pay.save()
messages.success(
request, "Thankyou, for using our services Your membership will run to the end of your billing cycle.")
else:
try:
if pay.paid:
membership = True
if pay.cancel_at_period_end:
cancel_at_period_end = True
except pay.DoesNotExist:
membership = False
return render(request, 'billing.html', {'membership': membership, 'pay': pay, 'cancel_at_period_end': cancel_at_period_end})
Traceback:
File "/Users/iamsuccessful/totdapp-2/totdapp/views.py" in billing
94. if pay.paid:
During handling of the above exception ('NoneType' object has no attribute 'paid'), another exception occurred:
File "/Users/iamsuccessful/totdapp/totdenv/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/Users/iamsuccessful/totdapp/totdenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/Users/iamsuccessful/totdapp/totdenv/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/iamsuccessful/totdapp/totdenv/lib/python3.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
21. return view_func(request, *args, **kwargs)
File "/Users/iamsuccessful/totdapp-2/totdapp/views.py" in billing
98. except pay.DoesNotExist or AttributeError:
Exception Type: AttributeError at /billing/
Exception Value: 'NoneType' object has no attribute 'DoesNotExist'
如果用户没有活动订阅,我希望重定向到 ('')(主页)。
从模型访问异常,例如payment.DoesNotExist
。
在 Python/Django 中,您应该将模型大写,例如class Payment(models.Model):
. 使用小写payment
会使您的代码难以阅读,并且更容易出错。
在您的回溯中,您有:
except pay.DoesNotExist or AttributeError:
这是不正确的,您应该使用要捕获的异常元组,例如:
except (payment.DoesNotExist, AttributeError):
payment.DoesNotExist or AttributeError
将简化为payment.DoesNotExist
,因此您永远不会遇到AttributeError
.
最后,DoesNotExist
当您执行Payment.objects.get(...)
. 你的线pay.paid
永远不会提高DoesNotExist
,但它可以提高AttributeError
的时候pay
是None
。您可以将代码简化为:
try:
if pay.paid:
membership = True
if pay.cancel_at_period_end:
cancel_at_period_end = True
except AttributeError:
membership = False
但是,如果你检查是否代码可能会更清晰pay
的None
。
if pay is not None:
if pay.paid:
membership = True
if pay.cancel_at_period_end:
cancel_at_period_end = True
else:
membership = False
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句