From 57192ac9d4e2890135a30d7e081d15b5bffdd5a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Freitag?= Date: Wed, 17 Jul 2024 14:07:19 +0200 Subject: [PATCH] Remove non-geo phone numbers from the SplitPhoneNumberWidget 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. --- phonenumber_field/formfields.py | 7 +++++-- tests/test_formfields.py | 3 +++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/phonenumber_field/formfields.py b/phonenumber_field/formfields.py index 920e4011..8737b5b0 100644 --- a/phonenumber_field/formfields.py +++ b/phonenumber_field/formfields.py @@ -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 @@ -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 } diff --git a/tests/test_formfields.py b/tests/test_formfields.py index 8d8eea91..e0195722 100644 --- a/tests/test_formfields.py +++ b/tests/test_formfields.py @@ -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 @@ -175,6 +176,8 @@ class TestForm(forms.Form): rendered = str(TestForm()) self.assertIn('', rendered) self.assertIn('', rendered) + for prefix in COUNTRY_CODES_FOR_NON_GEO_REGIONS: + self.assertNotIn(f"+{prefix}", rendered) def test_initial(self): class TestForm(forms.Form):