[Django]-Validators = [MinValueValidator] does not work in Django

28๐Ÿ‘

Your code:

from django.core.validators import MaxValueValidator, MinValueValidator

max_discount = models.FloatField( verbose_name=u'Maximum Discount', validators = [MinValueValidator(0.0)])

looks fine.
You should note though that

validators will not be run automatically when you save a model, but if
you are using a ModelForm, it will run your validators on any fields
that are included in your form.

See the docs for more info.

You can add some sort of html attribute validation in your form too, for example:

<input type="number" min="0.0">

to your server-side validation.

EDIT

If your form field is in the admin interface you can customize the widget (basically the HTML) for this field. You can see here how to add a custom widget to a field in the admin interface.

๐Ÿ‘คdoru

1๐Ÿ‘

I have done the same thing like this,

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

class Coupon(models.Model):
    code = models.CharField(max_length=50,
                               unique=True)
    valid_from = models.DateTimeField()
    valid_to = models.DateTimeField()
    discount = models.IntegerField(
                      validators=[MinValueValidator(0),
                                  MaxValueValidator(100)])
    active = models.BooleanField()
    def __str__(self):
        return self.code

I have set discount code like this,

discount = models.IntegerField(
                          validators=[MinValueValidator(0),
                                      MaxValueValidator(100)])

discount: The discount rate to apply (this is a percentage, so it takes values from 0 to 100). We use validators for this field to limit the minimum and maximum accepted values.

You can try this way might be working for you.

Thanks.

๐Ÿ‘คAhmed Ginani

0๐Ÿ‘

your problem is in the definition of the decimal.
You should do it like this:

validators = [MinValueValidator(Decimal('0.0'))]
๐Ÿ‘คThomas Alfonso

0๐Ÿ‘

You can create your own PositiveFloatField that extends FloatField and customize it as you like

class PositiveFloatField(FloatField):
description = _("Positive Float")

@cached_property
def validators(self):
    validators_ = super().validators

    validators_.append(validators.MinValueValidator(0.0))
    return validators_

def formfield(self, **kwargs):
    return super().formfield(**{
        'min_value': 0.0,
        **kwargs,
    })

Then in your model:

height = PositiveFloatField(verbose_name=_("Height"), null=True, blank=True)
๐Ÿ‘คjcobacho

Leave a comment