How to create a Django FloatField with maximum and minimum limits?

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.0), MaxValueValidator(1.0)],
)

EDIT:

However, that does not add a SQL constraint.

You can add SQL constraints as described here as CheckConstraints in Meta.constraints.

Combined example:

from django.core.validators import MaxValueValidator, MinValueValidator
from django.db.models import CheckConstraint, Q

class Foo(Model):
    myfloat = FloatField(min=0.0, max=1.0,
        # for checking in forms
        validators=[MinValueValidator(0.0), MaxValueValidator(1.0)],)

    class Meta:
        constraints = (
            # for checking in the DB
            CheckConstraint(
                check=Q(myfloat__gte=0.0) & Q(myfloat__lte=1.0),
                name="foo_myfloat_range"),
            )

Leave a Comment