Django从webhook参数更新“扩展用户配置文件”模型字段

时间:2018-01-13 17:46:57

标签: python django

我在用户付款后从我们的结算处理器获取了一个webhook。到目前为止,我已经成功地将webhook保存在模型中以便保存记录。但是,现在我需要将User account_paid字段更新为适当的状态。

我相信我已经正确地概述了这些步骤但我仍坚持实施代码。如何更新account_paid并确保它是正确的用户ID?

views.py

#@require_POST
def webhook(request):
    template_name = 'payment/index.html'

    hook = Webhook()
    hook.user = request.GET.get('clientAccnum')
    hook.clientSubacc = request.GET.get('clientSubacc')
    hook.eventType = request.GET.get('eventType')
    hook.eventGroupType = request.GET.get('eventGroupType')
    hook.subscriptionId = request.GET.get('subscriptionId')

    hook.timestamp = request.GET.get('timestamp')
    hook.timestamplocal = timezone.now()

    hook.save()

    print (hook.user, hook.clientSubacc, hook.timestamplocal)

    if hook.eventType == 'RenewalSuccess':
        #Update user account_level to Paid Account
        Profile.account_paid.update(True)

    else:
        #Update user account_level to Free
        Profile.account_paid.update(False)

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    account_level = models.BooleanField(default=False)

还没有错误信息,因为我现在正试图找出结构。目标是用一个有效的解决方案来完成这个问题。

*旁注: 我知道webhooks作为POST传递给URL但是现在我正在使用get纯粹用于调试目的。

1 个答案:

答案 0 :(得分:1)

Profile模型与User具有OneToOne关系,因此您可以简单地说:

hook.save()
hook.user.profile.account_paid = hook.eventType == 'RenewalSuccess'
hook.user.profile.save()