在Django模型中存储电话号码的最佳方法是什么

我这样存储电话号码model

phone_number = models.CharField(max_length=12)

用户将输入电话号码,而我将使用该电话号码。SMS Authentication此应用程序将在全球范围内使用。因此,我还需要国家代码。是CharField存储电话号码的好方法吗?而且,我该如何验证电话号码?

回答:

你实际上可能会研究国际标准格式E.164,例如Twilio推荐的格式(该服务具有通过REST请求发送SMS或电话的服务和API)。

这可能是最普遍的电话号码存储方式,尤其是在你使用国际号码的情况下。

你可以使用phonenumber_field库。它是Google的libphonenumber库的端口,可为Android的电话号码处理提供支持 https://github.com/stefanfoulis/django-phonenumber-field

在模型中:

from phonenumber_field.modelfields import PhoneNumberField

class Client(models.Model, Importable):

phone = PhoneNumberField(null=False, blank=False, unique=True)

通知:

from phonenumber_field.formfields import PhoneNumberField

class ClientForm(forms.Form):

phone = PhoneNumberField()

从对象字段获取电话作为字符串:

    client.phone.as_e164 

规范化电话字符串(用于测试和其他人员):

    from phonenumber_field.phonenumber import PhoneNumber

phone = PhoneNumber.from_string(phone_number=raw_phone, region='RU').as_e164

型号注意事项:E.164数字的最大字符长度为15。

为了进行验证,你可以采用某种格式组合,然后尝试立即联系该号码以进行验证。

我相信我在django项目中使用了以下内容:

class ReceiverForm(forms.ModelForm):

phone_number = forms.RegexField(regex=r'^\+?1?\d{9,15}$',

error_message = ("Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."))

编辑

看来此帖子对某些人很有用,将下面的评论整合到更完整的答案中似乎是值得的。根据jpotter6,你还可以在模型上执行以下操作:

models.py:

from django.core.validators import RegexValidator

class PhoneModel(models.Model):

...

phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")

phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list

以上是 在Django模型中存储电话号码的最佳方法是什么 的全部内容, 来源链接: utcz.com/qa/434417.html

回到顶部