Django: how do i substract numbers from another number and return the new_value in django
Question:
I have a model field called main_all_earning
and it looks like this main_all_earning = models.IntegerField(default=0)
, I also have a form where user are allowed to input any amount they want to withdraw from main_all_earning
, I have written the logic for it to subtract the value from the form which is called amount
from the main_all_earning
, but the main_all_earning does not update. What could be the issue?
Views.py:
def withdrawal_request(request):
user = request.user
profile = Profile.objects.get(user=user)
main_all_earning = profile.main_all_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 ...:
pass
else:
new_form.save()
main_all_earning = main_all_earning - new_form.amount
return redirect("core:withdrawal-request")
else:
...
context = { "form":form, "main_all_earning":main_all_earning,}
return render(request, "core/withdrawal-request.html", context)
Answers:
You set the main_all_earning
variable here:
main_all_earning = main_all_earning - new_form.amount
But you don’t actually set it on the profile or save it:
profile.main_all_earning = main_all_earning - new_form.amount
profile.save()
You need to save it on the profile like this
## chain the main_all_earning to the profile object
profile.main_all_earning = main_all_earning - new_form.amount
## Save the new value
profile.save()
I have a model field called main_all_earning
and it looks like this main_all_earning = models.IntegerField(default=0)
, I also have a form where user are allowed to input any amount they want to withdraw from main_all_earning
, I have written the logic for it to subtract the value from the form which is called amount
from the main_all_earning
, but the main_all_earning does not update. What could be the issue?
Views.py:
def withdrawal_request(request):
user = request.user
profile = Profile.objects.get(user=user)
main_all_earning = profile.main_all_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 ...:
pass
else:
new_form.save()
main_all_earning = main_all_earning - new_form.amount
return redirect("core:withdrawal-request")
else:
...
context = { "form":form, "main_all_earning":main_all_earning,}
return render(request, "core/withdrawal-request.html", context)
You set the main_all_earning
variable here:
main_all_earning = main_all_earning - new_form.amount
But you don’t actually set it on the profile or save it:
profile.main_all_earning = main_all_earning - new_form.amount
profile.save()
You need to save it on the profile like this
## chain the main_all_earning to the profile object
profile.main_all_earning = main_all_earning - new_form.amount
## Save the new value
profile.save()