Django Models Number Field

Question:

In Django I’m trying to create a model which will contain a field for player’s shirt numbers and was wondering if there is a way to restrict the field to be only numerical inputs. Currently I have in the models.py

number = models.CharField(max_length=2)

Is there a different field to CharField that will allow me to restrict the input to only numbers?

Asked By: Edward Knight

||

Answers:

One of the cool things about Django that it provides you with different types of models read about them here.

For your case try something like this

number = models.IntegerField()

You can read more about the IntegerField here

Answered By: Khaled Al-Ansari

There a number of fields rather than CharField in Django either in case of models or modelfields you use for forms:

In case of Integers you use: number = models.IntegerField()

or even

number = models.FloatField(), in case you want to represent price of a specific commodity.Its usefull in billing softwares.

There is also somemore like BigInteger field in case you wanted more nos

For detailed reference check:https://docs.djangoproject.com/en/1.11/ref/models/fields/

Answered By: Kurian Benoy

If you’re using serializers, you can use validators for these cases. For example, for a 10-digit CharField, you can have a validator like this :

def postalcode_validator(value):
    rule = re.compile(r'^d{10}$')
    if not rule.search(value):
        raise serializers.ValidationError("Postal code format must be XXXXXXXXXX")
    return value

Then, you can use this validator with your serializer’s CharField:

# serializers.py
...
postal_code = serializers.CharField(validators=[postalcode_validator])

Moreover, validators can be used with model fields as well just like the above example.

Answered By: Winston

Player’s shirt numbers should need only positive numbers.

PositiveBigIntegerField allows values from 0 to 9223372036854775807:

number = models.PositiveBigIntegerField()

PositiveIntegerField allows values from 0 to 2147483647:

number = models.PositiveIntegerField()

PositiveSmallIntegerField allows values from 0 to 32767:

number = models.PositiveSmallIntegerField()

In addition, there are no "NegativeIntegerField", "NegativeBigIntegerField" and "NegativeSmallIntegerField" in Django.

Answered By: Kai – Kazuya Ito