我正在使用derek73提供的phone number MultiWidget。问题是:它在POST中放置了三个单独的值 - 我应该如何将它们重新组合成一个值?
class USPhoneNumberMultiWidget(forms.MultiWidget):
"""
A Widget that splits US Phone number input into three <input type='text'> boxes.
"""
def __init__(self,attrs=None):
widgets = (
forms.TextInput(attrs={'size':'3','maxlength':'3', 'class':'phone'}),
forms.TextInput(attrs={'size':'3','maxlength':'3', 'class':'phone'}),
forms.TextInput(attrs={'size':'4','maxlength':'4', 'class':'phone'}),
)
super(USPhoneNumberMultiWidget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
return value.split('-')
return (None,None,None)
def value_from_datadict(self, data, files, name):
value = [u'',u'',u'']
# look for keys like name_1, get the index from the end
# and make a new list for the string replacement values
for d in filter(lambda x: x.startswith(name), data):
index = int(d[len(name)+1:])
value[index] = data[d]
if value[0] == value[1] == value[2] == u'':
return None
return u'%s-%s-%s' % tuple(value)
class UserForm(forms.ModelForm):
email = forms.EmailField(max_length=30,
widget=forms.TextInput(attrs={"class":"text"}))
first_name = forms.CharField(max_length=max_length_for_att(User, 'first_name'),
widget=forms.TextInput(attrs={"class":"text"}))
last_name = forms.CharField(max_length=max_length_for_att(User, 'last_name'),
widget=forms.TextInput(attrs={"class":"text"}))
phone = USPhoneNumberField(label="Phone",
widget=USPhoneNumberMultiWidget())
class Meta:
model = User
fields = ('email', 'first_name', 'last_name', 'phone', )
答案 0 :(得分:1)
查看USPhoneNumberField的clean() method。
答案 1 :(得分:1)
确保您访问form.cleaned_data
而不是request.POST
的数据。