开发者

Combine values from MultiWidget into one field for POST

开发者 https://www.devze.com 2023-01-17 09:35 出处:网络
I\'m using the phone number MultiWidget provided by derek73. Question is: it puts three separate values in the POST - how should I recombine them into one value?

I'm using the phone number MultiWidget provided by derek73. Question is: it puts three separate values in the POST - how should I recombine them into one value?

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', )


Look at the USPhoneNumberField's clean() method.


Make sure you are accessing the data from form.cleaned_data and not request.POST.

0

精彩评论

暂无评论...
验证码 换一张
取 消