Skip to content

Commit b746061

Browse files
Allow restricting PhoneNumberPrefixWidget country choices
1 parent 8ad812c commit b746061

File tree

2 files changed

+36
-5
lines changed

2 files changed

+36
-5
lines changed

phonenumber_field/widgets.py

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,16 @@ def localized_choices(language):
4545
class PhonePrefixSelect(Select):
4646
initial = None
4747

48-
def __init__(self, initial=None, attrs=None):
48+
def __init__(self, initial=None, attrs=None, choices=None):
4949
language = translation.get_language() or settings.LANGUAGE_CODE
50-
choices = localized_choices(language)
50+
if choices is None:
51+
choices = localized_choices(language)
52+
choices.sort(key=lambda item: item[1])
5153
if initial is None:
5254
initial = getattr(settings, "PHONENUMBER_DEFAULT_REGION", None)
5355
if initial in REGION_CODE_TO_COUNTRY_CODE:
5456
self.initial = initial
55-
super().__init__(attrs=attrs, choices=sorted(choices, key=lambda item: item[1]))
57+
super().__init__(attrs=attrs, choices=choices)
5658

5759
def get_context(self, name, value, attrs):
5860
attrs = (attrs or {}).copy()
@@ -67,9 +69,23 @@ class PhoneNumberPrefixWidget(MultiWidget):
6769
- an input for local phone number
6870
"""
6971

70-
def __init__(self, attrs=None, initial=None, country_attrs=None, number_attrs=None):
72+
def __init__(
73+
self,
74+
attrs=None,
75+
initial=None,
76+
country_attrs=None,
77+
country_choices=None,
78+
number_attrs=None,
79+
):
80+
"""
81+
:param country_choices: Limit the country choices.
82+
:type country_choices: list of 2-tuple, optional
83+
The first element is the value, which must match a country code
84+
recognized by the phonenumbers project.
85+
The second element is the label.
86+
"""
7187
widgets = (
72-
PhonePrefixSelect(initial, attrs=country_attrs),
88+
PhonePrefixSelect(initial, attrs=country_attrs, choices=country_choices),
7389
TextInput(attrs=number_attrs),
7490
)
7591
super().__init__(widgets, attrs)

tests/test_widgets.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,21 @@ def test_custom_attrs(self):
223223
'<input type="text" name="widget_1" class="number-input">', html, count=1
224224
)
225225

226+
def test_custom_choices(self):
227+
widget = PhoneNumberPrefixWidget(
228+
country_choices=[("FR", "France"), ("BE", "Belgium")]
229+
)
230+
self.assertHTMLEqual(
231+
widget.render(name="widget", value=None),
232+
"""
233+
<select name="widget_0">
234+
<option value="FR">France</option>
235+
<option value="BE">Belgium</option>
236+
</select>
237+
<input name="widget_1" type="text">
238+
""",
239+
)
240+
226241

227242
class PhoneNumberInternationalFallbackWidgetTest(SimpleTestCase):
228243
def test_fallback_widget_switches_between_national_and_international(self):

0 commit comments

Comments
 (0)