Skip to content

Commit

Permalink
Remove non-geo phone numbers from the SplitPhoneNumberWidget
Browse files Browse the repository at this point in the history
The COUNTRY_CODE_TO_REGION_CODE dict contains values that are not
specific to a region code: the COUNTRY_CODES_FOR_NON_GEO_REGIONS. These
country codes are international, and are not a good fit for the
SplitPhoneNumberWidget, which offers to select a region, then fill in
the national number.
  • Loading branch information
francoisfreitag committed Feb 9, 2025
1 parent 6d4e40c commit 57192ac
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
7 changes: 5 additions & 2 deletions phonenumber_field/formfields.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from django.utils import translation
from django.utils.text import format_lazy
from django.utils.translation import pgettext, pgettext_lazy
from phonenumbers import COUNTRY_CODE_TO_REGION_CODE
from phonenumbers import COUNTRY_CODE_TO_REGION_CODE, COUNTRY_CODES_FOR_NON_GEO_REGIONS

from phonenumber_field import widgets
from phonenumber_field.phonenumber import to_python, validate_region
Expand All @@ -17,10 +17,13 @@
except ModuleNotFoundError:
babel = None # type: ignore

GEO_COUNTRY_CODE_TO_REGION_CODE = COUNTRY_CODE_TO_REGION_CODE.copy()
for country_code in COUNTRY_CODES_FOR_NON_GEO_REGIONS:
del GEO_COUNTRY_CODE_TO_REGION_CODE[country_code]
# ISO 3166-1 alpha-2 to national prefix
REGION_CODE_TO_COUNTRY_CODE = {
region_code: country_code
for country_code, region_codes in COUNTRY_CODE_TO_REGION_CODE.items()
for country_code, region_codes in GEO_COUNTRY_CODE_TO_REGION_CODE.items()
for region_code in region_codes
}

Expand Down
3 changes: 3 additions & 0 deletions tests/test_formfields.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from django.test import SimpleTestCase, override_settings
from django.utils import translation
from django.utils.functional import lazy
from phonenumbers import COUNTRY_CODES_FOR_NON_GEO_REGIONS

from phonenumber_field.formfields import PhoneNumberField, SplitPhoneNumberField
from phonenumber_field.phonenumber import PhoneNumber
Expand Down Expand Up @@ -175,6 +176,8 @@ class TestForm(forms.Form):
rendered = str(TestForm())
self.assertIn('<option value="" selected>---------</option>', rendered)
self.assertIn('<option value="CN">China +86</option>', rendered)
for prefix in COUNTRY_CODES_FOR_NON_GEO_REGIONS:
self.assertNotIn(f"+{prefix}", rendered)

def test_initial(self):
class TestForm(forms.Form):
Expand Down

0 comments on commit 57192ac

Please sign in to comment.