Better error handling for gettext and gettext_lazy issues
|Reported by:||Manuel Saelices||Owned by:|
|Cc:||Triage Stage:||Ready for checkin|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
It's very common get confused in use of
gettext_lazy functions. An usual error was to use
gettext at import time, for example, in any of this cases:
- In a parameter of
from django.utils.translation import ugettext as _ ... LANGUAGE_CHOICES = (('es', _('Spanish')), ('en', _('English')),)
- In class or field definition of a
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 (35)
comment:5 follow-up: 8 Changed 9 years ago by
|Owner:||changed from Manuel Saelices to Malcolm Tredinnick|
|Triage Stage:||Unreviewed → Accepted|
comment:23 Changed 3 years ago by
|Patch needs improvement:||unset|
|Type:||New feature → Cleanup/optimization|
comment:29 Changed 3 years ago by
|Owner:||set to Claude Paroz <claude@…>|
|Status:||new → closed|