diff --git a/CHANGELOG.rst b/CHANGELOG.rst index e07d0507..bcf2a470 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -6,6 +6,7 @@ UNRELEASED * Set the default region of ``phonenumber_field.formfields.PhoneNumberField`` to ``PHONENUMER_DEFAULT_REGION``. +* Use PHONENUMBER_DEFAULT_REGION for example phone number in form field errors. * Add support for Django 4.0 * Add Persian (farsi) translations. * Update uk_AR translations diff --git a/phonenumber_field/formfields.py b/phonenumber_field/formfields.py index 0e487af0..0a6e2fc5 100644 --- a/phonenumber_field/formfields.py +++ b/phonenumber_field/formfields.py @@ -21,8 +21,8 @@ def __init__(self, *args, region=None, **kwargs): self.region = region or getattr(settings, "PHONENUMBER_DEFAULT_REGION", None) if "invalid" not in self.error_messages: - if region: - number = phonenumbers.example_number(region) + if self.region: + number = phonenumbers.example_number(self.region) example_number = to_python(number).as_national # Translators: {example_number} is a national phone number. error_message = _( diff --git a/tests/test_formfields.py b/tests/test_formfields.py index d2e74355..ad35746e 100644 --- a/tests/test_formfields.py +++ b/tests/test_formfields.py @@ -1,7 +1,7 @@ from unittest import mock from django import forms -from django.test import SimpleTestCase +from django.test import SimpleTestCase, override_settings from django.utils.functional import lazy from phonenumber_field.formfields import PhoneNumberField @@ -20,6 +20,23 @@ class PhoneNumberForm(forms.Form): form.errors, {"number": ["Enter a valid phone number (e.g. +12125552368)."]} ) + @override_settings(PHONENUMBER_DEFAULT_REGION="FR") + def test_error_message_uses_default_region(self): + class PhoneNumberForm(forms.Form): + number = PhoneNumberField() + + form = PhoneNumberForm({"number": "invalid"}) + self.assertIs(form.is_valid(), False) + self.assertEqual( + form.errors, + { + "number": [ + "Enter a valid phone number (e.g. 01 23 45 67 89) " + "or a number with an international call prefix." + ] + }, + ) + def test_override_error_message(self): class MyPhoneNumberField(PhoneNumberField): default_error_messages = {"invalid": "MY INVALID MESSAGE!"}