request.user是不是让我对当前用户进行更改?

时间:2017-11-07 13:52:00

标签: django django-views

在我的视图功能中,我正在尝试对当前用户进行2次修改;通过将模型字段is_premium_subscriber标记为True并将其添加到名为Premium Agents的组中,将其视为高级订阅者。

然而,这些更改似乎没有在我的views.py中注册!这是我的代码:

def payment_response(request):
    new_charge = PremiumSubscriptionCharge()

    if request.method == "POST":
        ... Some code here

    try:

        ... lots of code here

        new_charge.agent = request.user  # This line is working fine, meaning request.user is properly assigned to the current user

        request.user.is_premium_subscriber = True  # This is not working, is_premium_subscriber is still false after the request

        premium_agent_group = Group.objects.get(name='Premium Agents')
        premium_agent_group.user_set.add(request.user)  # This is not working either, the current user does not get added to the group.

        request.user.save()  # I don't know if this is necessary, but I put it here just in case.


    except stripe.error.CardError as ce:
        ... some code

    else:
        ... some code

我的用户模型供参考。我通过继承AbstractUser创建了一个自定义用户模型......这可能导致了这个问题吗?

class Agent(AbstractUser):
    is_premium_subscriber = models.BooleanField(default=False)

完整视图功能:

def payment_response(request):
    new_charge = PremiumSubscriptionCharge()

    if request.method == "POST":
        token = request.POST.get("stripeToken")

    try:

        customer = stripe.Customer.create(
            email = request.user.email,
            source = token,
        )
        charge = stripe.Charge.create(
            amount = 1500,
            currency = 'cad',
            customer = customer.id,
            description = "Agent Premium Subscription"
        )

        subscription = stripe.Subscription.create(
            customer=customer.id,
            items=[
                {
                    "plan": "premiumagent",
                },
            ],
        )


        new_charge.stripe_charge_id = charge.id
        new_charge.agent = request.user
        new_charge.customer = charge.customer
        new_charge.stripe_subscription_id = subscription.id
        request.user.is_premium_subscriber = True
        premium_agent_group = Group.objects.get(name='Premium Agents')
        premium_agent_group.user_set.add(request.user)
        request.user.save()


    except stripe.error.CardError as ce:
        return False, ce

    else:
        new_charge.save()
        return redirect("payment_success")

1 个答案:

答案 0 :(得分:0)

好的,我正在研究别的东西,回到它,现在它正在发挥作用。什么的感谢那些评论的人。