When I do
investment.basic_interest
I get 0. Why is it returning 0? I feel my save method is not properly written. Any idea where the problem is coming from?
class Investment(models.Model):
basic_deposit_amount = models.IntegerField(null=True)
basic_interest = models.IntegerField(null=True)
def save(self, *args, **kwargs):
self.basic_interest = self.basic_deposit_amount * 365 * 0.02/2 #calculated field.
super(Investment, self).save(*args, **kwargs)
Views
def create_investment_view(request):
if request.method == 'POST':
basic_investment_form = BasicInvestmentForm(request.POST)
if basic_investment_form.is_valid():
investment = basic_investment_form.save(commit=False)
investment.basic_investment_return = investment.basic_deposit_amount
print(investment.basic_interest)
print(investment.basic_investment_return)
print(investment.basic_deposit_amount)
investment.is_active = True
investment.save()
messages.success(request, 'your basic investment of {} is successfull '.format(investment.basic_deposit_amount))
else:
messages.success(request, 'your investment is not successfull! Try again.')
else:
basic_investment_form = BasicInvestmentForm()
context = {'basic_investment_form': basic_investment_form}
return render(request, 'create-basic-investment.html', context)
CodePudding user response:
It depends on where you are checking the value of investment.basic_interest
in your code. The piece of code you have is executed only when the instance is saved (after the save() method is called).
def test_view(request):
investment = Investment()
investment.basic_deposit_amount = 100
print(investment.basic_interest) # Prints 0
investment.save()
print(investment.basic_interest) # Prints 365.0
CodePudding user response:
You need to return what super()
method does. Add return
to last line:
def save(self, *args, **kwargs):
self.basic_interest = self.basic_deposit_amount * 365 * 0.02/2 #calculated field.
return super(Investment, self).save(*args, **kwargs)