2016-07-13 2 views
1

У меня есть модель с атрибутом, как это:Перевод с форматом строки во время импорта

new = models.BooleanField(default=False, verbose_name=_("Is new"), 
help_text=_("By default product is marked as new by {0} days since creation.") 
.format(settings.PRODUCT_IS_NEW_EXPIRATION_DAYS)) 

К сожалению, это работает для команды runserver, но когда я хочу запустить проверить его failes и я получаю следующее сообщение об ошибке:

django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time.

Эта ошибка ясна. Я пытаюсь использовать переводы, прежде чем приложения будут готовы.

Возможно ли иметь перевод, который требует форматирования строки во время импорта?

Edit: Traceback:

File "./manage.py", line 9, in <module> 
execute_from_command_line(sys.argv) 
File "django/core/management/__init__.py", line 354, in execute_from_command_line 
utility.execute() 
File "django/core/management/__init__.py", line 328, in execute 
django.setup() 
File "django/__init__.py", line 18, in setup 
apps.populate(settings.INSTALLED_APPS) 
File "django/apps/registry.py", line 85, in populate 
app_config = AppConfig.create(entry) 
File "django/apps/config.py", line 86, in create 
module = import_module(entry) 
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module 
__import__(name) 
File "haystack/__init__.py", line 57, in <module> 
signal_processor_class = loading.import_class(signal_processor_path) 
File "haystack/utils/loading.py", line 32, in import_class 
module_itself = importlib.import_module(module_path) 
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module 
__import__(name) 
File "utils/signals.py", line 12, in <module> 
from products.models import Products 
File "products/models/__init__.py", line 2, in <module> 
from .carousel import ProductCarousel, ProductCarouselImage 
File "products/models/carousel.py", line 10, in <module> 
from products.models.product import Products 
File "products/models/product.py", line 210, in <module> 
class Products(models.Model): 
File "products/models/product.py", line 241, in Products 
help_text=(ugettext("By default product is marked as new by {0} days since creation.")).format(
File "django/utils/translation/__init__.py", line 84, in ugettext 
return _trans.ugettext(message) 
File "django/utils/translation/trans_real.py", line 330, in ugettext 
return do_translate(message, 'ugettext') 
File "django/utils/translation/trans_real.py", line 307, in do_translate 
_default = _default or translation(settings.LANGUAGE_CODE) 
File "django/utils/translation/trans_real.py", line 209, in translation 
_translations[language] = DjangoTranslation(language) 
File "django/utils/translation/trans_real.py", line 118, in __init__ 
self._add_installed_apps_translations() 
File "django/utils/translation/trans_real.py", line 159, in _add_installed_apps_translations 
"The translation infrastructure cannot be initialized before the " 
django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time. 
+0

Является ли это с помощью '' ugettext' или ugettext_lazy'? – Sayse

+0

Нет никакой разницы, если это 'ugettext' или' ugettext_lazy'. Такая же ошибка. – Darkowic

+1

Я надеялся, что формат ленивого прокси-объекта обработал бы это. Я отредактировал ваш вопрос, чтобы, надеюсь, сделать его более ясным, пожалуйста, не стесняйтесь откатываться, если вы считаете, что это неверно. – Sayse

ответ

0

Я попытался прокомментировать пост, но я не могу, так как я не хватает репутации. Вы пытались сначала форматировать help_text, а затем перевести его? Что-то вроде этого:

help_text = _(
    "By default product is marked as new by {} days since creation.".format(
     settings.PRODUCT_IS_NEW_EXPIRATION_DAYS 
    ) 
) 
new = models.BooleanField(default=False, verbose_name=_("Is new"), 
    help_text=help_text) 

Примечание: .format находится внутри ugettext

+0

Вот проблема, которую вы не можете сделать. При компиляции в эту строку будет вставляться 'settings.PRODUCT_IS_NEW_EXPIRATION_DAYS'. В следующем шаге, когда Django пытается его перевести, он будет терпеть неудачу, потому что django не сможет найти msgid. «По умолчанию продукт помечается как новый на 90 дней с момента создания». (Правильный идентификатор «По умолчанию продукт помечается как новый через {} дней с момента создания». – Darkowic