From ee1dd714191450232b64f8bf3d659c2fc5004d3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Freitag?= Date: Thu, 21 Dec 2023 12:38:01 +0100 Subject: [PATCH] Make PhoneNumberPrefixSelect use the provided region 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. --- phonenumber_field/widgets.py | 9 ++++++++- tests/test_widgets.py | 5 +++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/phonenumber_field/widgets.py b/phonenumber_field/widgets.py index 60fdf377..c11b59b3 100644 --- a/phonenumber_field/widgets.py +++ b/phonenumber_field/widgets.py @@ -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` @@ -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) diff --git a/tests/test_widgets.py b/tests/test_widgets.py index afea369e..988d50c5 100644 --- a/tests/test_widgets.py +++ b/tests/test_widgets.py @@ -67,6 +67,11 @@ def test_uses_default_region_as_initial(self): self.assertIn('', rendered) self.assertIn('', rendered) + def test_uses_kwarg_region_as_prefix(self): + rendered = PhoneNumberPrefixWidget(region="CN").render("", "") + self.assertIn('', rendered) + self.assertIn('', rendered) + def test_no_initial(self): rendered = PhoneNumberPrefixWidget().render("", "") self.assertIn('', rendered)