简体   繁体   English

如何在 django 中执行数学运算?

[英]how do i perform a math operation in django?

i am trying to calculate the new_balance when a user withdraw any amount from thier main balance .当用户从他们的main balance中提取任何金额时,我正在尝试计算new_balance

i am trying to perform this operation when the form is being submitted but i do not know if this is the perfect way to perform this operations.我正在尝试在提交表单时执行此操作,但我不知道这是否是执行此操作的完美方式。 This is what i am trying to achive.这就是我想要达到的目标。

def withdrawal_request(request):
    ...
    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)

I was actually missing one more line我实际上又少了一行

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")
        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)

You're returning at the end of the upper else statement, so you can't reach the line where you update your context .您将在上方else语句的末尾返回,因此您无法到达更新context的行。 In Python a function exits after returning.在 Python 中,函数在返回后退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM