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()
从object字段中获取phone作为字符串:
client.phone.as_e164
规范化电话字符串(用于测试和其他工作人员):
from phonenumber_field.phonenumber import PhoneNumber
phone = PhoneNumber.from_string(phone_number=raw_phone, region='RU').as_e164
Phone by regexp
对于您的模型有一个注意事项: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 is allowed."))
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
# "models.py"
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
class Contact(models.Model):
phone = PhoneNumberField()
然后,在“admin.py"中注册“Contact":
# "admin.py"
from django.contrib import admin
from .models import Contact
@admin.register(Contact)
class ContactAdmin(admin.ModelAdmin):
pass
# "admin.py"
from django.contrib import admin
from .models import Contact
from django import forms
from phonenumber_field.widgets import PhoneNumberPrefixWidget
class ContactForm(forms.ModelForm):
class Meta:
widgets = {
'phone': PhoneNumberPrefixWidget(),
}
@admin.register(Contact)
class ContactAdmin(admin.ModelAdmin):
form = ContactForm
# "admin.py"
from django.contrib import admin
from .models import Contact
from django import forms
from phonenumber_field.widgets import PhoneNumberPrefixWidget
class ContactForm(forms.ModelForm):
class Meta:
widgets = { # Here
'phone': PhoneNumberPrefixWidget(initial='US'),
}
@admin.register(Contact)
class ContactAdmin(admin.ModelAdmin):
form = ContactForm