Ticket #13997: 13997.diff

File 13997.diff, 2.1 KB (added by Preston Timmons, 14 years ago)

Documented using the Multiwidget with single value fields

  • docs/ref/forms/widgets.txt

    diff --git a/docs/ref/forms/widgets.txt b/docs/ref/forms/widgets.txt
    index dbdf109..02ac15a 100644
    a b commonly used groups of widgets:  
    150150
    151151.. class:: MultiWidget
    152152
    153     Wrapper around multiple other widgets
     153    Wrapper around multiple other widgets. This is usually used in conjunction
     154    with the ``MultiValueField``.
     155
     156.. note::
     157
     158    If you want to use a ``MultiWidget`` for a field that is not a subclass
     159    of :class:`MultiValueField`, such as the ``us.forms.USPhoneNumberField`` from
     160    the ``localflavor`` package, then you must override the ``value_from_datadict``
     161    method of your widget to return a single value appropriate for the
     162    field.
     163
     164    .. code-block:: python
     165
     166        class USSplitPhoneWidget(forms.MultiWidget):
     167
     168            widgets = (
     169                forms.TextInput(attrs={'size':'3','maxlength':'3'}),
     170                forms.TextInput(attrs={'size':'3','maxlength':'3'}),
     171                forms.TextInput(attrs={'size':'4','maxlength':'4'}),
     172            )
     173
     174            def decompress(self, value):
     175                """
     176                Accepts a single value which is extracted to populate the
     177                provided widgets.
     178                """
     179                if value:
     180                    return value.split('-')
     181                return (None,None,None)
     182
     183            def value_from_datadict(self, data, files, name):
     184                """
     185                Modify the widget to return a single value for the
     186                USPhoneNumberField.
     187                """
     188                values = super(USSplitPhoneWidget, self).value_from_datadict(data, files, name)
     189                values = (x.replace("-", "") for x in values)
     190                if all(values):
     191                    return u'%s-%s-%s' % tuple(values)
     192                return ""
     193
     194            def format_output(self, rendered_widgets):
     195                return '<span class="lparen">(</span>%s<span class="rparen">)</span>%s<span class="phone-dash">-</span>%s' % tuple(rendered_widgets)
    154196
    155197.. class:: SplitDateTimeWidget
    156198
Back to Top