MultiValueField and labels

655 views
Skip to first unread message

Zack

unread,
Feb 24, 2008, 12:21:00 AM2/24/08
to Django users
Hi,

If I have these custom field, widget, and form:

class PersonField(forms.MultiValueField):
def __init__(self, *args, **kwargs):
fields = (
forms.CharField(label='Title'),
forms.CharField(label='First name'),
forms.CharField(label='Middle initial'),
forms.CharField(label='Last name'),
forms.CharField(label='Suffix'),
forms.CharField(label='Credential')
)
widgets = PersonWidget()
super(PersonField, self).__init__(fields, widget=widgets,
*args, **kwargs)

def compress(self, data_list):
return data_list

class PersonWidget(forms.widgets.MultiWidget):
def __init__(self):
widgets = (
forms.widgets.TextInput(),
forms.widgets.TextInput(),
forms.widgets.TextInput(),
forms.widgets.TextInput(),
forms.widgets.TextInput(),
forms.widgets.TextInput()
)
super(PersonWidget, self).__init__(widgets)

def decompress(self, value):
if value:
return value
return [None, None, None, None, None]

class TestPersonForm(forms.Form):
contact = PersonField(label='Contact Info')

Why doesn't
>>> f = TestPersonForm()
>>> f.as_p()
have labels generated for all the CharFields as defined in
PersonField?
I get the label for the PersonField ('Contact Info') but none of the
labels for the subfields. Any help greatly appreciated.

Malcolm Tredinnick

unread,
Feb 24, 2008, 2:08:06 AM2/24/08
to django...@googlegroups.com

On Sat, 2008-02-23 at 21:21 -0800, Zack wrote:
[...]

> Why doesn't
> >>> f = TestPersonForm()
> >>> f.as_p()
> have labels generated for all the CharFields as defined in
> PersonField?

Because that's not how MultiWidget works.

You can see from the code that the labels on widgets are created by the
Form._html_output() method, not by the widget rendering methods (which
makes sense, as often the label side of things is changed). You can also
see that MultiWidget's rendering method just calls the rendering method
on each of its sub-widgets.

If you want your sub-fields to render with labels and everything, make
them separate fields and then use the form's clean() method to combine
their individual values back into a single value (since Form.clean() is
designed for normalising values that come from multiple fields).

Regards,
Malcolm

--
Tolkien is hobbit-forming.
http://www.pointy-stick.com/blog/

Reply all
Reply to author
Forward
0 new messages