Missing one-to-one relation between MultiValueField fields and MultiWidget widgets

40 views
Skip to first unread message

Vlastimil Zíma

unread,
Jan 29, 2018, 8:09:35 AM1/29/18
to Django developers (Contributions to Django itself)
Hi,

I've been playing around with a field and widget for phone number having two, prefix and subscriber, inputs. I've noticed some HTML attributes, such as maxlength, which the widgets normally have, get lost in the MultiValueField/MultiWidget interface. The MultiValueField contains two parts - the fields and a MultiWidget. Each of the field has it's own widget and provides it with custom attributes (the `Field.widget_attrs` method), but this benefit gets lost, once they're wrapped into a MultiValueField, because only it's own `widget_attrs` is used.

Is there a reason, why MultiValueField's MultiWidget's widgets are not connected to the MultiValueField's fields' widgets? Can we provide such link in order to benefit from existing HTML attributes' tweak's of individual fields?

Minimal working example:
from django import forms

class PhoneWidget(forms.MultiWidget):
   
def __init__(self, widgets=(), attrs=None):
       
if not widgets:
            widgets
= (forms.TextInput({'class': 'number-prefix'}),
                      
forms.TextInput({'class': 'subscriber'}))
       
super(PhoneWidget, self).__init__(widgets, attrs)

   
def decompress(self, value):
       
return (value or '').split('.', 1)


class PhoneField(forms.MultiValueField):
    widget
= PhoneWidget
   
def __init__(self, fields=(), *args, **kwargs):
        fields
= (forms.CharField(max_length=4), forms.CharField())
       
super(PhoneField, self).__init__(fields, *args, **kwargs)

   
def compress(self, data_list):
       
return '.'.join(data_list)

class PhoneForm(forms.Form):
    number
= PhoneField()

str
(PhoneForm())

The prefix input in the resulting HTML lacks the "maxlength" attribute, even though corresponding field have this limit defined.

Regards
Vlastimil
Reply all
Reply to author
Forward
0 new messages