简体   繁体   English

django charField 只接受数字

[英]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 ?我有这个 django charField,我希望它只接受数字。我们如何在 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 .我希望 total_employees 只接受来自我的客户的数字而不是字符串。我也想检查 api 端。

There is BigIntegerField which you could use instead.您可以使用BigIntegerField代替。

If not and you REALLY MUST use a CharField you could use validators .如果没有,你真的必须使用 CharField 你可以使用验证器 Create a validator which tries to convert the field to int, wrapped in a try except block.创建一个尝试将字段转换为 int 的验证器,包装在 try except 块中。 In the except you raise a ValidationError if its not int.如果不是 int,则在 except 中引发ValidationError

You could make it into a IntegerField or BigIntegerField at form level you make a form for the model.您可以在表单级别将其变为 IntegerField 或 BigIntegerField,您可以为模型制作表单。

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

total_employees should need only positive numbers . total_employees应该只需要正数

PositiveBigIntegerField allows values from 0 to 9223372036854775807 : PositiveBigIntegerField允许从 0 到 9223372036854775807 的值:

total_employees = models.PositiveBigIntegerField()

PositiveIntegerField allows values from 0 to 2147483647 : PositiveIntegerField允许从 0 到 2147483647 的值:

total_employees = models.PositiveIntegerField()

PositiveSmallIntegerField allows values from 0 to 32767 : PositiveSmallIntegerField允许从 0 到 32767 的值:

total_employees = models.PositiveSmallIntegerField()

In addition, there are no "NegativeIntegerField" , "NegativeBigIntegerField" and "NegativeSmallIntegerField" in Django .此外, Django中没有“NegativeIntegerField”“NegativeBigIntegerField”“NegativeSmallIntegerField”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM