我在模型中存储一个电话号码,就像这样:

phone_number = models.CharField(max_length=12)

用户将输入一个电话号码,我将使用该电话号码进行SMS身份验证。该应用程序将被全局使用。所以我还需要国家代码。CharField是存储电话号码的好方法吗?以及,我如何验证电话号码?


当前回答

在模型中的phone字段使用CharField,在localflavor应用程序中使用表单验证:

https://docs.djangoproject.com/en/1.7/topics/localflavor/

从2021-12-07开始,LocalFlavor似乎不再是Django的一部分了。

其他回答

这完全取决于你对电话号码的理解。电话号码是国家特有的。一些国家的本地风味包包含他们自己的“电话号码字段”。因此,如果你是特定国家的OK,你应该看看localflavor包(类US .models. phonenumberfield为美国情况,等等)。

否则,你可以检查当地的口味,以获得所有国家的最大长度。Localflavor还有一些表单字段,可以与国家代码一起使用来验证电话号码。

实际上,您可以研究国际标准化格式E.164,例如Twilio推荐的格式(Twilio提供了通过REST请求发送短信或电话的服务和API)。

这可能是存储电话号码的最通用方法,特别是如果您使用的是国际号码。

Phone by PhoneNumberField You can use the phonenumber_field library. It is a port of Google's libphonenumber library, which powers Android's phone number handling. See django-phonenumber-field. In the model: from phonenumber_field.modelfields import PhoneNumberField class Client(models.Model, Importable): phone = PhoneNumberField(null=False, blank=False, unique=True) In the form: from phonenumber_field.formfields import PhoneNumberField class ClientForm(forms.Form): phone = PhoneNumberField() Get the phone as a string from an object field: client.phone.as_e164 Normalize the 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 Phone by regexp One note for your model: E.164 numbers have a maximum character length of 15. To validate, you can employ some combination of formatting and then attempting to contact the number immediately to verify. I believe I used something like the following in 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 is 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-phonenumber-field:

pip install django-phonenumber-field

这个解决方案对我很有效:

首先安装django-phone-field。命令:

pip install django-phone-field

然后在models.py文件中:

from phone_field import PhoneField
...

class Client(models.Model):
    ...
    phone_number = PhoneField(blank=True, help_text='Contact phone number')

在文件settings.py中:

INSTALLED_APPS = [...,
                  'phone_field'
]

最后是这样的:

我将描述我所使用的:

验证:字符串包含超过5位数字。

清除:删除所有非数字符号,只向数据库写入数字。我很幸运,因为在我的国家(俄罗斯),每个人的电话号码都是10位数。所以我在数据库中只存储了10个数字。如果您正在编写一个多国应用程序,那么您应该进行全面验证。

渲染:我编写了一个自定义模板标记,以便在模板中很好地渲染它。甚至像图片一样渲染它-这是更安全的防止短信垃圾邮件。