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 | A widget that splits phone number input into three fields. |
| 169 | """ |
| 170 | def __init__(self, widgets=None, attrs=None): |
| 171 | if not widgets: |
| 172 | widgets = ( |
| 173 | forms.TextInput(attrs={'size':'3','maxlength':'3'}), |
| 174 | forms.TextInput(attrs={'size':'3','maxlength':'3'}), |
| 175 | forms.TextInput(attrs={'size':'4','maxlength':'4'}), |
| 176 | ) |
| 177 | super(USSplitPhoneWidget, self).__init__(widgets, attrs) |
| 178 | |
| 179 | def decompress(self, value): |
| 180 | """ |
| 181 | Accepts a single value which is extracted to populate the |
| 182 | provided widgets. |
| 183 | """ |
| 184 | if value: |
| 185 | return value.split('-') |
| 186 | return ("","","") |
| 187 | |
| 188 | def value_from_datadict(self, data, files, name): |
| 189 | """ |
| 190 | Modify the widget to return a single value for the |
| 191 | USPhoneNumberField. |
| 192 | """ |
| 193 | values = super(USSplitPhoneWidget, self).value_from_datadict(data, files, name) |
| 194 | values = (x.replace("-", "") for x in values) |
| 195 | return u'%s-%s-%s' % tuple(values) |
| 196 | |
| 197 | def format_output(self, rendered_widgets): |
| 198 | return '<span class="lparen">(</span>%s<span class="rparen">)</span>%s<span class="phone-dash">-</span>%s' % tuple(rendered_widgets) |
| 199 | |
| 200 | You would use this widget in a form as follows: |
| 201 | |
| 202 | .. code-block:: python |
| 203 | |
| 204 | from django.contrib.localflavor.us.forms import USPhoneNumberField |
| 205 | |
| 206 | class MyForm(forms.Form): |
| 207 | phone = USPhoneNumberField(label="Phone", |
| 208 | widget=USSplitPhoneWidget()) |