I\'m storing some floating-point data in my Django models, and only a certain range of values are meaningful. Therefore, I\'d like to impose these limits at both the model a
The answers so far describe how to make forms validate. You can also put validators in the model. Use MinValueValidator and MaxValueValidator.
For example:
from django.core.validators import MaxValueValidator, MinValueValidator
...
weight = models.FloatField(
validators=[MinValueValidator(0.9), MaxValueValidator(58)],
)
I don't think that adds SQL constraints, tho.
If you need constraint on form level you can pass min_value
and max_value
to form field:
myfloat = forms.FloatField(min_value=0.0, max_value=1.0)
But if you need to move it up to model level you have to extend base models.FloatField
class
class MinMaxFloat(models.FloatField):
def __init__(self, min_value=None, max_value=None, *args, **kwargs):
self.min_value, self.max_value = min_value, max_value
super(MinMaxFloat, self).__init__(*args, **kwargs)
def formfield(self, **kwargs):
defaults = {'min_value': self.min_value, 'max_value' : self.max_value}
defaults.update(kwargs)
return super(MinMaxFloat, self).formfield(**defaults)
Then you can use it in models
class Foo(models.Model):
myfloat = MinMaxFloat(min_value=0.0, max_value=1.0)