Skip to content

Commit

Permalink
Accept per-widget attrs for PhoneNumberPrefixWidget
Browse files Browse the repository at this point in the history
  • Loading branch information
francoisfreitag committed Jun 17, 2022
1 parent 0ab8b7c commit 8f2f9ee
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
11 changes: 7 additions & 4 deletions phonenumber_field/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ def localized_choices(language):
class PhonePrefixSelect(Select):
initial = None

def __init__(self, initial=None):
def __init__(self, initial=None, attrs=None):
language = translation.get_language() or settings.LANGUAGE_CODE
choices = localized_choices(language)
if initial is None:
initial = getattr(settings, "PHONENUMBER_DEFAULT_REGION", None)
if initial in REGION_CODE_TO_COUNTRY_CODE:
self.initial = initial
super().__init__(choices=sorted(choices, key=lambda item: item[1]))
super().__init__(attrs=attrs, choices=sorted(choices, key=lambda item: item[1]))

def get_context(self, name, value, attrs):
attrs = (attrs or {}).copy()
Expand All @@ -66,8 +66,11 @@ class PhoneNumberPrefixWidget(MultiWidget):
- an input for local phone number
"""

def __init__(self, attrs=None, initial=None):
widgets = (PhonePrefixSelect(initial), TextInput())
def __init__(self, attrs=None, initial=None, country_attrs=None, number_attrs=None):
widgets = (
PhonePrefixSelect(initial, attrs=country_attrs),
TextInput(attrs=number_attrs),
)
super().__init__(widgets, attrs)

def decompress(self, value):
Expand Down
11 changes: 11 additions & 0 deletions tests/test_widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,17 @@ def test_maxlength_not_in_select(self):
html = widget.render(name="widget", value=None, attrs={"maxlength": 32})
self.assertIn('<select name="widget_0">', html)

def test_custom_attrs(self):
widget = PhoneNumberPrefixWidget(
country_attrs={"class": "country-input"},
number_attrs={"class": "number-input"},
)
html = widget.render(name="widget", value=None)
self.assertIn('<select name="widget_0" class="country-input">', html)
self.assertInHTML(
'<input type="text" name="widget_1" class="number-input">', html, count=1
)


class PhoneNumberInternationalFallbackWidgetTest(SimpleTestCase):
def test_fallback_widget_switches_between_national_and_international(self):
Expand Down

0 comments on commit 8f2f9ee

Please sign in to comment.