Code

Ticket #13997: 13997.2.diff

File 13997.2.diff, 2.6 KB (added by prestontimmons, 3 years ago)

Modified the docs with better example and gave example usage.

Line 
1diff --git a/docs/ref/forms/widgets.txt b/docs/ref/forms/widgets.txt
2index dbdf109..e34b3fe 100644
3--- a/docs/ref/forms/widgets.txt
4+++ b/docs/ref/forms/widgets.txt
5@@ -150,7 +150,62 @@ commonly used groups of widgets:
6 
7 .. class:: MultiWidget
8 
9-    Wrapper around multiple other widgets
10+    Wrapper around multiple other widgets. This is usually used in conjunction
11+    with the ``MultiValueField``.
12+
13+.. note::
14+
15+    If you want to use a ``MultiWidget`` for a field that is not a subclass
16+    of :class:`MultiValueField`, such as the ``us.forms.USPhoneNumberField`` from
17+    the ``localflavor`` package, then you must override the ``value_from_datadict``
18+    method of your widget to return a single value appropriate for the
19+    field.
20+
21+    .. code-block:: python
22+
23+        class USSplitPhoneWidget(forms.MultiWidget):
24+            """
25+            A widget that splits phone number input into three fields.
26+            """
27+            def __init__(self, widgets=None, attrs=None):
28+                if not widgets:
29+                    widgets = (
30+                        forms.TextInput(attrs={'size':'3','maxlength':'3'}),
31+                        forms.TextInput(attrs={'size':'3','maxlength':'3'}),
32+                        forms.TextInput(attrs={'size':'4','maxlength':'4'}),
33+                    )
34+                super(USSplitPhoneWidget, self).__init__(widgets, attrs)
35+
36+            def decompress(self, value):
37+                """
38+                Accepts a single value which is extracted to populate the
39+                provided widgets.
40+                """
41+                if value:
42+                    return value.split('-')
43+                return ("","","")
44+
45+            def value_from_datadict(self, data, files, name):
46+                """
47+                Modify the widget to return a single value for the
48+                USPhoneNumberField.
49+                """
50+                values = super(USSplitPhoneWidget, self).value_from_datadict(data, files, name)
51+                values = (x.replace("-", "") for x in values)
52+                return u'%s-%s-%s' % tuple(values)
53+
54+            def format_output(self, rendered_widgets):
55+                return '<span class="lparen">(</span>%s<span class="rparen">)</span>%s<span class="phone-dash">-</span>%s' % tuple(rendered_widgets)
56+
57+    You would use this widget in a form as follows:
58+
59+    .. code-block:: python
60+
61+        from django.contrib.localflavor.us.forms import USPhoneNumberField
62+
63+        class MyForm(forms.Form):
64+            phone = USPhoneNumberField(label="Phone",
65+                 widget=USSplitPhoneWidget())
66 
67 .. class:: SplitDateTimeWidget
68