I want to set the minimum value for FloatField in Django so that the form field does not accept negative value. In case of Integers I changed the datatype to PositiveIntegerField but minimum value is not working in case of float field.
from django.core.validators import MaxValueValidator, MinValueValidator
max_discount = models.FloatField( verbose_name=u'Maximum Discount', validators = [MinValueValidator(0.0)])
Django forms submit only if it contains CSRF tokens. It uses uses a clean and easy approach to validate data. The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
Writing validators A validator is a callable that takes a value and raises a ValidationError if it doesn't meet some criteria. Validators can be useful for reusing validation logic between different types of fields.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With