user13180201
user13180201

Reputation: 37

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.

Upvotes: 2

Views: 12026

Answers (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.

Upvotes: 2

Sayed Hisham
Sayed Hisham

Reputation: 51

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 '] 

Upvotes: 5

Dean Elliott
Dean Elliott

Reputation: 1323

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.

Upvotes: 3

Related Questions