Beno
Beno

Reputation: 576

How to limit values of IntergerField with Django?

i wonder if it's possible to limit values of an IntegerField with Django.

My code in forms.py :

class RatingForm(forms.Form):
    rate = forms.IntegerField(label='Noter')

Upvotes: 0

Views: 500

Answers (4)

Beno
Beno

Reputation: 576

This code works :

class RatingForm(forms.Form):
    rate = forms.IntegerField(label='Noter', validators=[MaxValueValidator(5), MinValueValidator(0)])

Thanks all !!

Upvotes: 0

akimul
akimul

Reputation: 329

You can use max_value as specified in the django doc. https://docs.djangoproject.com/en/1.11/ref/forms/fields/#integerfield

class RatingForm(forms.Form):
    rate = forms.IntegerField(label='Noter', max_value=100)

Upvotes: 1

Exprator
Exprator

Reputation: 27513

  from django.core.validators import MaxValueValidator, MinValueValidator

  class RatingForm(forms.Form):
    rate = forms.IntegerField(label='Noter',
            validators=[
                MaxValueValidator(100),
                MinValueValidator(1)
            ]
         )

use django's built in validators

Upvotes: 1

dirkgroten
dirkgroten

Reputation: 20682

Use min_value and max_value, inside your form: see the Django docs

Upvotes: 0

Related Questions