Как выполнить математическую операцию в django?

я пытаюсь вычислить new_balance когда пользователь снимает любую сумму со своего main balance.

я пытаюсь выполнить эту операцию, когда форма отправляется, но я не знаю, является ли это идеальным способом для выполнения этой операции. Вот чего я пытаюсь добиться.

@login_required
def withdrawal_request(request):
    user = request.user
    profile = Profile.objects.get(user=user)
    total_investment = PurchasedPackage.objects.filter(paid=True, user=request.user).aggregate(Sum("investment_package__price"))['investment_package__price__sum']
    bonus_earning = profile.earning_point
    total_ref_earning = profile.referral_point
    bonus_point = profile.bonus_point
    social_share_points = profile.social_share_points
    
    pending_payout = WithdrawalRequest.objects.filter(user=request.user, status="pending").aggregate(Sum("amount"))['amount__sum']
    if pending_payout == None:
        pending_payout = 0
        
    total_payout = WithdrawalRequest.objects.filter(user=request.user, status="settled").aggregate(Sum("amount"))['amount__sum']

    try:
        all_earning = total_investment + bonus_earning + total_ref_earning + bonus_point + social_share_points
    except:
        all_earning = bonus_earning + total_ref_earning

    try:
        new_balance = total_investment + bonus_earning + total_ref_earning + bonus_point + social_share_points
    except:
        new_balance = bonus_earning + total_ref_earning

    if request.method == "POST":
        form = WithWithdrawalRequestForm(request.POST)
        if form.is_valid():
            new_form = form.save(commit=False)
            new_form.user = request.user

            if new_form.amount > all_earning:
                messages.warning(request, "You cannot withdraw more than what is in your wallet balance.")
                return redirect("core:withdrawal-request")
            elif pending_payout > new_balance:
                messages.warning(request, "You have reached your wallet limit")
                return redirect("core:withdrawal-request")
            else:
                new_form.save()
                new_balance = new_balance - new_form.amount
                messages.success(request, f"Withdrawal Request Is Been Processed...")
                return redirect("core:withdrawal-request")
        
    else:
        form = WithWithdrawalRequestForm(request.POST)
        

    context = {
            "form":form,
            "new_balance":new_balance,
        }
    return render(request, "core/withdrawal-request.html", context)

кажется, что эта строка, которая находится после сохранения формы " balance = new_balance - new_form.amount " ничего не делает, и это то, что я хочу использовать для получения new_balance, тогда новый_баланс не обновляется. Что я могу сделать дальше?

        else:
            new_form.save()
            new_balance = new_balance - new_form.amount
            messages.success(request, f"Withdrawal Request Is Been Processed...")
            return redirect("core:withdrawal-request")
    
else:
    form = WithWithdrawalRequestForm(request.POST)
    

context = {
        "form":form,
        "new_balance":new_balance,
    }
return render(request, "core/withdrawal-request.html", context)

Вы возвращаетесь в конце верхнего оператора else, поэтому вы не можете достичь строки, где вы обновляете context. В Python функция завершается после возврата.

Мне не хватало еще одной строки

else:
   new_form.save()
   request.user.profile.main_all_earning = main_all_earning - new_form.amount
   request.user.profile.save()
   messages.success(request, f"Withdrawal Request Is Been Processed...")
   return redirect("core:withdrawal-request")
Вернуться на верх