'django charField accepting only numbers

I have this django charField and i want it to accept only numbers .How can we achieve this in django ?

class Xyz(models.Model):
     total_employees = models.CharField(max_length=100)

I want total_employees to accept only numbers and not strings from my client .I want to put a check on api end too .



Solution 1:[1]

There is BigIntegerField which you could use instead.

If not and you REALLY MUST use a CharField you could use validators. Create a validator which tries to convert the field to int, wrapped in a try except block. In the except you raise a ValidationError if its not int.

Solution 2:[2]

You could make it into a IntegerField or BigIntegerField at form level you make a form for the model.

class Xyzform(ModelForm):
     total_employees =forms.IntegerField()
    class Meta:
        model=Xyz
        fields=['total_employees ']  

or you may add a validation at form level:

from django.core.exceptions import ValidationError
 # paste in your models.py
 def only_int(value): 
    if value.isdigit()==False:
        raise ValidationError('ID contains characters')

class Xyzform(ModelForm):
     total_employees =forms.CharField(validators=[only_int])
    class Meta:
        model=Xyz
        fields=['total_employees '] 

Solution 3:[3]

total_employees should need only positive numbers.

PositiveBigIntegerField allows values from 0 to 9223372036854775807:

total_employees = models.PositiveBigIntegerField()

PositiveIntegerField allows values from 0 to 2147483647:

total_employees = models.PositiveIntegerField()

PositiveSmallIntegerField allows values from 0 to 32767:

total_employees = models.PositiveSmallIntegerField()

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dean Elliott
Solution 2 Sayed Hisham
Solution 3 Kai - Kazuya Ito