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.
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.
- [Django]-Django substr / substring in templates
- [Django]-Django REST Framework : "This field is required." with required=False and unique_together
- [Django]-Django model constraint for related objects
0๐
your problem is in the definition of the decimal.
You should do it like this:
validators = [MinValueValidator(Decimal('0.0'))]
- [Django]-Error: No module named staticfiles
- [Django]-Django {% if forloop.first %} question
- [Django]-Django custom management commands: AttributeError: 'module' object has no attribute 'Command'
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)
- [Django]-Django + Ajax
- [Django]-Django models: Only permit one entry in a model?
- [Django]-How to run celery as a daemon in production?