django validator min max value

Django provides validators that allow us to validate the input data for our models. We can use the MinValueValidator and MaxValueValidator to set minimum and maximum values for a field.

Here are the steps to use these validators:

  1. Import the necessary modules:
from django.core.validators import MinValueValidator, MaxValueValidator
  1. Define the field in your model, and include the validators as arguments:
class MyModel(models.Model):
    my_field = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100)])

In this example, the my_field is an IntegerField that can have a minimum value of 0 and a maximum value of 100.

  1. Perform the migrations to update the database schema:
python manage.py makemigrations
python manage.py migrate
  1. Now, when you try to save a model instance with a value outside the specified range, Django will raise a ValidationError and prevent the data from being saved.

That's it! With these steps, you can use the MinValueValidator and MaxValueValidator to set minimum and maximum values for a field in Django.