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

Use the default region’s format in form errors #483

Merged
merged 1 commit into from
Jan 11, 2022
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
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