It is easy to get the current language (e.g. en) anywhere in a django app: django.utils.translation.get_lanaguage()
But how do I get the current locale (e.g. en_US or en_GB)?
It is easy to get the current language (e.g. en) anywhere in a django app: django.utils.translation.get_lanaguage()
But how do I get the current locale (e.g. en_US or en_GB)?
Did you try to_locale()
?
from django.utils.translation import to_locale, get_language
to_locale(get_language())
The distinction between language
and locale
(in Django, at least) is just a matter of formatting. Both en
and en-us
are languages, and if en-us
is the currently selected language then that will be returned by get_language()
.
So your problem seems to be that Django is not setting the current language the way you expect. There's a long list of techniques Django uses to try and figure out the language to use, so I suggest working your way down that to see why the language isn't what you expect.
For example:
If a base language is available but the sublanguage specified is not, Django uses the base language. For example, if a user specifies
de-at
(Austrian German) but Django only hasde
available, Django usesde
.
Django's django.utils.translation.to_locale()
expects a "language name" like en-us
and will convert that to a "locale name" like en_US
.
Source code: https://github.com/django/django/blob/master/django/utils/translation/init.py#L271-L284
It basically just does some string manipulation.
If your "language name" is just a simple language code like en
, it will return just en
. If you want to convert en
to a locale like en_US.UTF8
, you will have to write your own to_locale()
function. You'll have to determine what locale you want for the language code en
. Example:
LANG_TO_LOCALE = {
'en': 'en_US.UTF8',
'nl': 'nl_NL.UTF8',
'es': 'es_ES.UTF8'
}
def lang_to_locale(language_code):
return LANG_TO_LOCALE.get(language_code)
Depending on your taste you might for example want to get the locale en_GB.UTF8
instead of en_US.UTF8
for the language code en
.
This then can be used to set the locale in Python:
import locale
locale.setlocale(locale.LC_ALL, lang_to_locale('nl'))
And then you can get a month name in the desired language:
from datetime import datetime
print(datetime.strftime(datetime.now(), '%B')) # Prints month name in Dutch
To make this work you need to have the appropriate locale packages installed on your system. On Ubuntu you can do this with sudo dpkg-reconfigure locales
.
In the relevant (virtual) environment:
python
>>> import locale
>>> locale.getlocale()
e.g. ('en_GB', 'UTF-8')
© 2022 - 2024 — McMap. All rights reserved.