且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Django 模型中存储电话号码的***方式是什么

更新时间:2023-02-17 16:18:16

您实际上可能会研究国际标准化格式 E.164例如由 Twilio 推荐(他们有一个服务和一个 API,用于通过 REST 请求发送短信或电话).

You might actually look into the internationally standardized format E.164, recommended by Twilio for example (who have a service and an API for sending SMS or phone-calls via REST requests).

这可能是最通用的电话号码存储方式,尤其是当您使用国际号码时.

This is likely to be the most universal way to store phone numbers, in particular if you have international numbers work with.

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

You can use phonenumber_field library. It is port of Google's libphonenumber library, which powers Android's phone number handling 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()

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

Get phone as string from object field:

    client.phone.as_e164 

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

Normolize phone string (for tests and other staff):

    from phonenumber_field.phonenumber import PhoneNumber
    phone = PhoneNumber.from_string(phone_number=raw_phone, region='RU').as_e164

2.通过正则表达式电话

关于您的模型的一个说明:E.164 数字的最大字符长度为 15.

2. Phone by regexp

One note for your model: E.164 numbers have a max character length of 15.

要进行验证,您可以采用某种格式组合,然后尝试立即联系号码进行验证.

To validate, you can employ some combination of formatting and then attempting to contact the number immediately to verify.

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

I believe I used something like the following on my django project:

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,您也可以对模型执行以下操作:

It appears that this post has been useful to some folks, and it seems worth it to integrate the comment below into a more full-fledged answer. As per jpotter6, you can do something like the following on your models as well:

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