I am working on a Django project which is localized and works fine in many languages. Now for a reason I need to call ugettext from its shell.
Here is what I did:
>>> from django.conf import settings
>>> settings.LANGUAGE_CODE
u'fa-ir'
>>> from django.utils.translation import ugettext as _
>>> print _("Schedule & Details")
Schedule & Details
As you see the phrase "Schedule & Details" did not print in Persian language.
Is it possible to translate a phrase and then print it inside Django shell?
Django's normal translation feature depends on django.middleware.locale.LocaleMiddleware, but middleware runs as part of the request / response cycle. Since you are in an interactive shell and there is no request object the middleware can't do its job.
If you manually activate the language in your shell you should see translation behaving as expected:
>>> from django.utils.translation import activate, ugettext as _
>>>
>>> activate('fa-ir')
>>> print _("Schedule & Details")
Of course, instead of hard-coding 'fa-ir' you could load it from settings.LANGUAGE_CODE if you wish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With