1

表格.py

class PhoneForm(forms.ModelForm):         
    number1 = forms.IntegerField(required=False,error_messages={'invalid':'Enter a valid phone number'})
    number2 = forms.IntegerField(required=False,error_messages={'invalid':'Enter a valid phone number'})
    number3 = forms.IntegerField(required=False,error_messages={'invalid':'Enter a valid phone number'})
    class Meta:
        model = PhoneInfo
        fields = ['name1','number1','name2','number2','name3','number3','emergency','emergency_number']

模型.py

class PhoneInfo(models.Model):    
    user = models.ForeignKey(User, null=True)
    name1 = models.CharField('Name', max_length=100, null=True, blank=True)
    number1 = models.CharField('Number',max_length=20, null=True, blank=True)
    name2 =  models.CharField('Name', max_length=100, null=True, blank=True)
    number2 = models.CharField('Number', max_length=20, null=True, blank=True)
    name3 = models.CharField('Name', max_length=100, null=True, blank=True)
    number3 = models.CharField('Number',max_length=20, null=True, blank=True)
    emergency = models.CharField('Emergency', max_length=100, null=True, blank=True)
    emergency_number = models.CharField('Emergency Number',max_length=20, null=True, blank=True)

nmber1、number2 和 number3 用于保存 11 位电话号码。我的问题是,如果我在保存“0”后将第 1 位添加为“0”从表单字段中消失。我在第 1 位后添加“0”正在保存和显示。问题在于:08854215452 第一个零在保存后消失。我想在保存带有 STD 代码的电话号码时也显示这一点。

Traceback:
File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  101.                             request.path_info)
File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
  252.                     sub_match = pattern.resolve(new_path)
File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
  252.                     sub_match = pattern.resolve(new_path)
File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
  158.             return ResolverMatch(self.callback, args, kwargs, self.name)
File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py" in _get_callback
  164.             self._callback = get_callable(self._callback_str)
File "/usr/lib/python2.7/site-packages/django/utils/functional.py" in wrapper
  124.         result = func(*args)
File "/usr/lib/python2.7/site-packages/django/core/urlresolvers.py" in get_callable
  91.                 lookup_view = getattr(import_module(mod_name), func_name)
File "/usr/lib/python2.7/site-packages/django/utils/importlib.py" in import_module
  35.     __import__(name)
File "/root/Projects/ir_uploaded_copy/ir/setting/views.py" in <module>
  22. from setting.forms import *
File "/root/Projects/ir_uploaded_copy/ir/setting/forms.py" in <module>
  151. class PhoneForm(forms.ModelForm):
File "/root/Projects/ir_uploaded_copy/ir/setting/forms.py" in PhoneForm
  162.     emergency_number = forms.RegexField(regex=r'^\+?(\d{3}-?\d+{7})$', error_messages = {'invalid':'Enter a valid phone number'})
File "/usr/lib/python2.7/site-packages/django/forms/fields.py" in __init__
  437.             regex = re.compile(regex)
File "/usr/lib/python2.7/re.py" in compile
  190.     return _compile(pattern, flags)
File "/usr/lib/python2.7/re.py" in _compile
  245.         raise error, v # invalid expression

Exception Type: error at /setting/call/
Exception Value: multiple repeat

谢谢

4

5 回答 5

2

切勿将电话号码另存为IntegerFields. 您看到的行为对于任何编程语言中的整数都是正常的。

>> myInt = 00001
>> print myInt
>> 1

你应该把它存储为什么?你要么 a) 写你自己的领域, b) 选择 CharField或选择一个RegexField

当谈到电话号码时,如果您在世界的某个特定地区,我通常更喜欢正则表达式字段,例如瑞典会有以下正则表达式:

phone_number = forms.RegexField(regex=r'^\+?(\d{3}-?\d+{7})$', error_messages = {'invalid_phonenumber': _("Not a valid Swedish phone number.")}
于 2013-07-30T08:06:41.610 回答
2

切勿将电话号码视为整数!始终使用 CharFields,如有必要,可能会进行一些验证。确保您不仅允许使用数字,还允许使用“-”、“”等。

您的 ModelForm 可能如下所示:

class PhoneForm(forms.ModelForm):
    class Meta:
        model = PhoneInfo
        fields = ['name1','number1','name2','number2','name3','number3','emergency','emergency_number']

    def clean_number1(self):
        n = self.cleaned_data.get('number1')
        for allowednondigit in '- ./':
            n.replace(allowednondigit, '')
        for char in n:
            if char not in '0123456789':
                raise forms.ValidationError("Please only use digits, spaces, dots, slash and dash characters")
        return n

这样,您在数据库中只存储数字(如果这是您真正想要的),同时仍然让您的用户按照他习惯的方式编写电话号码。

于 2013-07-30T08:06:54.247 回答
0

models.CharField由于这个确切的原因,我只见过存储在 s 中的电话号码。

forms.IntegerField不要在表单上使用,而是使用forms.CharField.

于 2013-07-30T08:07:52.523 回答
0

是 - 整数将忽略前导零。您可以将 0 设为隐式(实际上是隐式)或将其转换为文本字段。

于 2013-07-30T08:08:57.313 回答
0

我根据mawimawi 的回答发布了我的工作解决方案。

class PhoneForm(forms.ModelForm):
    class Meta:
        model = PhoneInfo
        fields = ['name1','number1','name2','number2','name3','number3','emergency','emergency_number']

    def clean_number1(self):
        n = self.cleaned_data.get('number1')
        allowed_characters = '0123456789- ./'
        for char in n:
            if char not in allowed_characters:
                raise forms.ValidationError("Please only use digits, spaces, dots, slash and dash characters")
        return n
于 2015-02-12T18:29:34.090 回答