Skip to content

Commit

Permalink
Use the default region’s format in form errors
Browse files Browse the repository at this point in the history
Instead of showing an international number, use a phone number
originating from the configured PHONENUMBER_DEFAULT_REGION.

Reviewed-by: thedrow
  • Loading branch information
francoisfreitag committed Jan 11, 2022
1 parent b78bdda commit 27e9d9b
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions phonenumber_field/formfields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = _(
Expand Down
19 changes: 18 additions & 1 deletion tests/test_formfields.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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!"}
Expand Down

0 comments on commit 27e9d9b

Please sign in to comment.