Django Stripe订阅配置遇subscriptions_stripecustomer不存在错误(CustomUser场景)
问题修复方案
1. 适配自定义用户模型的代码修改
你只需要修改views.py中用户模型的导入逻辑即可,你猜测的两处查询代码无需单独改动:
替换原来的默认User导入语句:
# 删掉这行 # from django.contrib.auth.models import User # 替换为以下两行 from django.contrib.auth import get_user_model User = get_user_model()
stripe_customer = StripeCustomer.objects.get(user=request.user)本身逻辑正确,request.user默认就是你自定义的CustomUser实例,和StripeCustomer的外键关联规则匹配user = User.objects.get(id=client_reference_id)替换导入后User已经指向你的自定义用户模型,直接保留即可
2. 解决subscriptions_stripecustomer表不存在报错
该报错的核心原因是StripeCustomer模型对应的数据库表还没有创建,按顺序执行以下操作即可:
- 先确认
subscriptions应用已经添加到settings.py的INSTALLED_APPS列表中 - 执行迁移生成命令:
python manage.py makemigrations subscriptions
- 执行迁移写入数据库:
python manage.py migrate
3. 可选优化(避免webhook运行异常)
建议给webhook中的用户查询逻辑增加异常捕获,避免无效请求触发500报错:
# Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed': session = event['data']['object'] client_reference_id = session.get('client_reference_id') stripe_customer_id = session.get('customer') stripe_subscription_id = session.get('subscription') # 增加异常捕获 try: user = User.objects.get(id=client_reference_id) StripeCustomer.objects.create( user=user, stripeCustomerId=stripe_customer_id, stripeSubscriptionId=stripe_subscription_id, ) print(user.username + ' just subscribed.') except User.DoesNotExist: return HttpResponse(status=400)
额外提示:你贴出的
stripe_webhook视图代码存在缩进错误,视图下的所有逻辑代码都需要缩进4格,否则运行时会直接抛出语法错误。
内容的提问来源于stack exchange,提问作者daylyroppo2
相关产品推荐
相关产品推荐

