Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only positive decimal numbers

Tags:

python

django

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?

like image 405
Houman Avatar asked Sep 12 '12 08:09

Houman


People also ask

How do you allow only positive numbers in the input number?

As we know, the <input type="number"> specifies a field for entering a number. If you want to restrict the <input> field to only positive numbers, you can use the min attribute.

How do you restrict decimals?

You can either use the ROUND function to limit decimal places in Excel, or you can use cell formatting to limit the number of decimal places displayed. While the ROUND function will amend the original value, using cell formatting will retain the exact original value.

What are positive numbers in decimals?

Positive decimal first and foremost is a value that is positive. That is, it is greater than 0. In the same way that a negative number is less than 0. Some people tend to consider the only decimal part of 2751.89105 to be the .

Can decimal be positive?

Negative and positive decimals can be compared just like fractions. Decimals are a part of a whole just like fractions are a part of a whole. Therefore, a positive decimal is ALWAYS greater than a negative decimal.


2 Answers

Use the MinValueValidator.

price = models.DecimalField(_(u'Price'), decimal_places=2, max_digits=12, validators=[MinValueValidator(Decimal('0.01'))]) 
like image 168
Alasdair Avatar answered Sep 21 '22 03:09

Alasdair


You could do something like this :

# ..... class priceForm(ModelForm):     price = forms.DecimalField(required=False, max_digits=6, min_value=0) 

This, also, is responsible for the validator value of 'price'.

like image 24
Nick Cuevas Avatar answered Sep 22 '22 03:09

Nick Cuevas