diff --git a/CHANGELOG.rst b/CHANGELOG.rst index ecfeeea1..c1a07055 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -4,10 +4,13 @@ CHANGELOG UNRELEASED ---------- +* Lazy load ``formfields.PhoneNumberField`` translation for ``invalid`` data. + **Backwards incompatible changes** * Drop support for end-of-life Django 3.0 + 5.1.0 (2021-04-02) ------------------ diff --git a/phonenumber_field/formfields.py b/phonenumber_field/formfields.py index 55659b29..5f880ee8 100644 --- a/phonenumber_field/formfields.py +++ b/phonenumber_field/formfields.py @@ -2,7 +2,8 @@ from django.core import validators from django.core.exceptions import ValidationError from django.forms.fields import CharField -from django.utils.translation import gettext as _ +from django.utils.text import format_lazy +from django.utils.translation import gettext_lazy as _ from phonenumber_field.phonenumber import to_python, validate_region from phonenumber_field.validators import validate_international_phonenumber @@ -31,8 +32,8 @@ def __init__(self, *args, region=None, **kwargs): example_number = "+12125552368" # Ghostbusters # Translators: {example_number} is an international phone number. error_message = _("Enter a valid phone number (e.g. {example_number}).") - self.error_messages["invalid"] = error_message.format( - example_number=example_number + self.error_messages["invalid"] = format_lazy( + error_message, example_number=example_number ) def to_python(self, value): diff --git a/tests/test_formfields.py b/tests/test_formfields.py index d207ed37..d2e74355 100644 --- a/tests/test_formfields.py +++ b/tests/test_formfields.py @@ -1,5 +1,8 @@ +from unittest import mock + from django import forms from django.test import SimpleTestCase +from django.utils.functional import lazy from phonenumber_field.formfields import PhoneNumberField @@ -45,3 +48,13 @@ class PhoneNumberForm(forms.Form): form = PhoneNumberForm({"number": ALGERIAN_PHONE_NUMBER}) self.assertTrue(form.is_valid()) self.assertEqual(ALGERIAN_PHONE_NUMBER, form.cleaned_data["number"]) + + def test_error_message_lazy(self): + def fail_gettext(msgid): + raise Exception("gettext was called unexpectedly.") + + with mock.patch( + "phonenumber_field.formfields._", + side_effect=lazy(fail_gettext, str), + ): + PhoneNumberField()