Better error handling for gettext and gettext_lazy issues
|Reported by:||msaelices||Owned by:|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||yes|
It's very common get confused in use of gettext and gettext_lazy functions. An usual error was to use gettext at import time, for example, in any of this cases:
- In a parameter of settings.py file:
from django.utils.translation import ugettext as _ ... LANGUAGE_CHOICES = (('es', _('Spanish')), ('en', _('English')),)
- In class or field definition of a models.py file:
from django.db import models from django.utils.translation import ugettext as _ class Author(models.Model): name = models.CharField(_(u'Name'), max_length=100)
In both cases, if you get an error, the error will be an ImportError usually in another part of code... This is very difficult to debug, because the real error should be "Incorrect use of gettext. You can't use gettext at import time".
The error is due to the fact of not all applications has been imported yet, and gettext resolution need to have all possible translation files loaded (django.po files), which implies loading of all applications. This causes a circular import error problem.
In this thread there is a discussion about this.
We are thinking in check in every call to gettext if django apps has been loaded (using django.db.models.loading.app_cache_ready()) and take one of this options:
- raise an representative error.
- return a dummy string.
I personally prefers first one, because gettext should be always called inside functions (at run time), and never at import time. I don't imagine a case of we need use gettext before that.
Change History (27)
comment:1 Changed 6 years ago by msaelices
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
comment:5 follow-up: ↓ 8 Changed 6 years ago by mtredinnick
- Owner changed from msaelices to mtredinnick
- Triage Stage changed from Unreviewed to Accepted