我正在尝试创建一个电话号码字段,遵循Django官方文档,但得到以下异常,我理解这是因为CharField并希望将其转换为整数。但我真的需要将它转换为整数或字符串,我无法将其转换为。我想要<Country code>-<Phone Number>X<Extn>
格式的电话号码。
以下是代码:
from django import forms
from django.core.validators import RegexValidator
from django.db import models
class PhoneWidget(forms.MultiWidget):
'''
Custom Form widget to display/input international phone numbers
'''
def __init__(self, *args, **kwargs): # pylint: disable=E1002
widgets = (
forms.RegexField(r'^[1-9]\d*', min_length=1, max_length=4),
forms.RegexField(r'^[1-9]\d*', min_length=7, max_length=10),
forms.RegexField(r'^\d+', min_length=0, max_length=5, required=False),
)
super(PhoneWidget, self).__init__(widgets, *args, **kwargs)
def decompress(self, value):
if value:
split_x = value[1:].split('x')
split_nos = split_x.strip().split('-')
return [split_nos[0], split_nos[1], split_x[1].strip()]
return ['', '', '']
class PhoneField(forms.MultiValueField):
'''
Custom field to keep international phone numbers
'''
def __init__(self, *args, **kwargs):
# Define one message for all fields.
error_messages = {
'incomplete': 'Enter a country code and phone number.',
}
# Or define a different message for each field.
fields = (
models.CharField(error_messages={'incomplete': 'Enter a country code.'},
validators=[RegexValidator(r'^[1-9]\d{3}$',
'Enter a valid country code (without leading Zeros).')]),
models.CharField(error_messages={'incomplete': 'Enter a phone number.'},
validators=[RegexValidator(r'^[1-9]\d{9}$',
'Enter a valid phone number (without leading Zeros).')]),
models.CharField(validators=[RegexValidator(r'^\d+$', 'Enter a valid extension.')],
null=True),
)
super(PhoneField, self).__init__(
self, error_messages=error_messages, fields=self.compress(fields),
require_all_fields=False, *args, **kwargs)
self.widget = PhoneWidget
def compress(self, data_list):
if data_list[2] != None and data_list[2] != '':
return '+%d-%d x %d' % (int(str(data_list[0])), int(str(data_list[1])), int(str(data_list[2])))
else:
return '+%d-%d' % (data_list[0], data_list[1])
但是得到这个例外:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.6
Exception Type: ValueError
Exception Value:
invalid literal for int() with base 10: '<django.db.models.fields.CharField>'
在压缩方法中,我是类型转换。感谢是否有人可以在这方面帮助我。
注意:我知道有一个可用于国际电话号码的开源库,可以稍微改写以解决我的目的,但我想自己做。