It's been quite some time and the community voted answer is good enough, based on Django built-ins, but here is another approach, problem specific, following the Django Project's documentation.
Create a custom validator
# app/models.py or create another file for custom validators, i.e. app/custom_validators.py
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _ # use if you support internationalization
def validate_interval(value):
if value < 0.0 or value > 1.0:
raise ValidationError(_('%(value)s must be in the range [0.0, 1.0]'), params={'value': value},)
Use your validator in your models
# app/models.py
class Foo(models.Model):
myfloat = models.FloatField(validators=[validate_interval])
You can even make the validator parametric to be more generic.
EDIT - IMPORTANT
Bare in mind that any validator is invoked during the form's clean()
method.
I.E. if you try to directly create an object without using a form, your validator will NOT be invoked.
There are those who don't recommend it but if you want to invoke validators while creating an object override the save method.
# app/models.py
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _ # use if you support internationalization
class Foo(models.Model):
def save(self, *args, **kwargs):
self.full_clean() # or clean
super().save(*args, **kwargs)
def validate_interval(value):
if value < 0.0 or value > 1.0:
raise ValidationError(_('%(value)s must be in the range [0.0, 1.0]'), params={'value': value},)
myfloat = models.FloatField(validators=[validate_interval])