Skip to content

Commit

Permalink
Make PhoneNumberPrefixSelect use the provided region
Browse files Browse the repository at this point in the history
Model fields and form fields accept a region keyword argument, and pass
it to their widget. When region is provided, initialize the country
selector in that region, chances are most users want to select it.
  • Loading branch information
francoisfreitag committed Dec 21, 2023
1 parent cb83645 commit 2e2eac5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
9 changes: 8 additions & 1 deletion phonenumber_field/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ def __init__(
country_attrs=None,
country_choices=None,
number_attrs=None,
region=None,
):
"""
:keyword dict attrs: See :attr:`~django.forms.Widget.attrs`
Expand All @@ -92,9 +93,15 @@ def __init__(
The second element is the label.
:keyword dict number_attrs: The :attr:`~django.forms.Widget.attrs` for
the local phone number :class:`~django.forms.TextInput`.
:keyword str region: 2-letter country code as defined in ISO 3166-1.
When not supplied, defaults to :setting:`PHONENUMBER_DEFAULT_REGION`
"""
widgets = (
PhonePrefixSelect(initial, attrs=country_attrs, choices=country_choices),
PhonePrefixSelect(
initial or region,
attrs=country_attrs,
choices=country_choices,
),
TextInput(attrs=number_attrs),
)
super().__init__(widgets, attrs)
Expand Down
5 changes: 5 additions & 0 deletions tests/test_widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ def test_uses_default_region_as_initial(self):
self.assertIn('<option value="">---------</option>', rendered)
self.assertIn('<option value="CN" selected>China +86</option>', rendered)

def test_uses_kwarg_region_as_prefix(self):
rendered = PhoneNumberPrefixWidget(region="CN").render("", "")
self.assertIn('<option value="">---------</option>', rendered)
self.assertIn('<option value="CN" selected>China +86</option>', rendered)

def test_no_initial(self):
rendered = PhoneNumberPrefixWidget().render("", "")
self.assertIn('<option value="" selected>---------</option>', rendered)
Expand Down

0 comments on commit 2e2eac5

Please sign in to comment.