Houman Houman - 2 months ago 43
Python Question

Allow only positive decimal numbers

Within my Django models I have created a decimal field like this:

price = models.DecimalField(_(u'Price'), decimal_places=2, max_digits=12)


Obviously it makes no sense for the price to be negative or zero. Is there a way to limit the decimal number to only positive numbers?

Or do I have to capture this using form validation?

Answer

Use the MinValueValidator.

price = models.DecimalField(_(u'Price'), decimal_places=2, max_digits=12, validators=[MinValueValidator(Decimal('0.01'))])
Comments