Allow only positive decimal numbers
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'.
In Django 2.2 you can add constraints to a model which will be applied in the migrations as a constraint on the database table:
from decimal import Decimal
from django.db import models
class Item(models.Model):
price = models.DecimalField( _(u'Price'), decimal_places=2, max_digits=12 )
class Meta:
constraints = [
models.CheckConstraint(check=models.Q(price__gt=Decimal('0')), name='price_gt_0'),
]
Note:
Validation of Constraints
In general constraints are not checked during
full_clean()
, and do not raiseValidationErrors
. Rather you’ll get a database integrity error onsave()
.
Use the MinValueValidator
.
price = models.DecimalField(_(u'Price'), decimal_places=2, max_digits=12, validators=[MinValueValidator(Decimal('0.01'))])