Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call ugettext from Django shell?

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?

like image 889
mahyard Avatar asked Oct 21 '25 11:10

mahyard


1 Answers

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.

like image 159
Chris Avatar answered Oct 24 '25 05:10

Chris