Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accept per-widget attrs for PhoneNumberPrefixWidget #502

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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