Skip to content

Commit

Permalink
Lazy load form field error message translation
Browse files Browse the repository at this point in the history
Follow pattern from Django form fields. Since fields are loaded at
import time, prevents calling into the translation machinery before
Django has completed its setup.

Thanks traviselam for reporting.

Reviewed-by: th3hamm0r
Reviewed-by: stefanfoulis
  • Loading branch information
francoisfreitag committed May 27, 2021
1 parent e653a09 commit 0947555
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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)
------------------

Expand Down
7 changes: 4 additions & 3 deletions phonenumber_field/formfields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down
13 changes: 13 additions & 0 deletions tests/test_formfields.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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()

0 comments on commit 0947555

Please sign in to comment.