Django电话号码表单字段出错

时间:2016-09-29 22:24:12

标签: python django django-forms

我正在构建一个包含电话号码字段的Django表单。我一直在提到这两个SO问题,以了解如何执行此操作:12。我创建了这个表单字段:

class ContactForm(forms.Form):
    phone = forms.RegexField(
        regex = r'^\+?[1-9]\d{1,14}$',
        #regex = r'\+?\d{10,14}$',
        error_messages = {'required', 'Phone number required'},
        widget = forms.TextInput(attrs={'class': 'form-control'})
    )

我在模板中显示字段:

<div>
    <label for="id_phone">Your Phone Number</label>
    {{ form.phone.errors }}
    {{ form.phone }}
</div>

我理解正则表达式正在做什么,他们看起来对我来说是正确的。但是,如果我使用其中任何一个,我就会收到此错误:

ValueError at /business/contact/
dictionary update sequence element #0 has length 8; 2 is required
...
Exception Location: /srv/http/example.com/venvs/dev/local/lib/python2.7/site-packages/django/forms/fields.py in __init__, line 125
(stacktrace...)
widget = forms.TextInput(attrs={'class': 'form-control'})
super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
super(CharField, self).__init__(*args, **kwargs)
messages.update(error_messages or {})
(end of stacktrace)

任何人都可以看到导致此错误的原因吗?它似乎是由正则表达式引起的。

1 个答案:

答案 0 :(得分:2)

我刚发现错误。它在这一行:

error_messages = {'required', 'Phone number required'},

我需要用“:”替换“,”:

error_messages = {'required': 'Phone number required'},