I have a Django model for a sweater and want to be able to enter the composition of materials used in the admin panel (say: “100% wool” or “50% wool, 50% cotton” or “50% wool, 45% cotton, 5% acryl”).
I have this model:
class Sweater(models.Model):
wool = models.IntegerField(max_length=3, default=100, verbose_name="wool (%)")
cotton = models.IntegerField(max_length=3, default=0, verbose_name="cotton (%)")
acryl = models.IntegerField(max_length=3, default=0, verbose_name="acryl (%)")
How and where do I assert that the sum of the wool, cotton and acryl values must be 100 so that a user can’t enter for example “100% wool, 100% cotton, 100% acryl”?
You should likely do it in at least two places. One to make sure you don’t get incorrect data in the model and one to let the user know the sum does not add up to 100%. The below handles checking the sum during form cleaning:
Hope that helps!