我在模型中存储一个电话号码,就像这样:
phone_number = models.CharField(max_length=12)
用户将输入一个电话号码,我将使用该电话号码进行SMS身份验证。该应用程序将被全局使用。所以我还需要国家代码。CharField是存储电话号码的好方法吗?以及,我如何验证电话号码?
我在模型中存储一个电话号码,就像这样:
phone_number = models.CharField(max_length=12)
用户将输入一个电话号码,我将使用该电话号码进行SMS身份验证。该应用程序将被全局使用。所以我还需要国家代码。CharField是存储电话号码的好方法吗?以及,我如何验证电话号码?
当前回答
验证很容易。给他们发一段代码让他们输入。
CharField是存储它的好方法。我不会太担心把电话号码规范化。
其他回答
在模型中的phone字段使用CharField,在localflavor应用程序中使用表单验证:
https://docs.djangoproject.com/en/1.7/topics/localflavor/
从2021-12-07开始,LocalFlavor似乎不再是Django的一部分了。
这完全取决于你对电话号码的理解。电话号码是国家特有的。一些国家的本地风味包包含他们自己的“电话号码字段”。因此,如果你是特定国家的OK,你应该看看localflavor包(类US .models. phonenumberfield为美国情况,等等)。
否则,你可以检查当地的口味,以获得所有国家的最大长度。Localflavor还有一些表单字段,可以与国家代码一起使用来验证电话号码。
验证很容易。给他们发一段代码让他们输入。
CharField是存储它的好方法。我不会太担心把电话号码规范化。
首先,需要安装电话号码Django包。
pip install django-phonenumber-field[phonenumbers]
接下来是将其添加到已安装的应用程序中:
INSTALLED_APPS = [
...
'phonenumber_field',
...
]
下面是如何在你的模型中使用它:
from phonenumber_field.modelfields import PhoneNumberField
class Artist(models.Model):
phone_number = PhoneNumberField()
实际上,您可以研究国际标准化格式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