[Fixed]-Django – default field value depends on other field value


perhaps add this to your Bill class?

def save(self, *args, **kwargs):
    if self.priceNoTax is None:
        self.priceNoTax = self.idAccount.idPackage.price
    super(Bill, self).save(*args, **kwargs)


Why do you need it to be a field? Do you see a reason where someone would want to change the total price without changing the price and tax to the corresponding values? If it doesn’t really need to be a field, you can just make it a method.

class Bill(models.Model):
     date = models.DateField(default=datetime.now())
     tax = models.FloatField(default=0.20)
     priceNoTax = models.IntegerField()
     idAccount = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name="Account")

     def priceTax(self):
       return self.priceNoTax + (self.priceNoTax*self.tax)

     def __str__(self):
         return self.date

You can still use it the same way in templates with {{ bill.priceTax }}. In code you would need to use bill.priceTax().

This way, the price with tax should stay up-to-date no matter how the tax or price without tax changes.

You can also use @property decorator to avoid having to call it as a function in code.

def priceTax(self):
   return self.priceNoTax + (self.priceNoTax*self.tax)

For more see https://docs.djangoproject.com/en/2.0/topics/db/models/#model-methods



@kichik answered how to display the default value using template tag, and I recommend to implement auto-calculation by javascript.

Of course, you will have to validate user input or implement save() method as @Chris Curvey said.

Leave a comment