Getting the current locale in django - django

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 has de available, Django uses de.

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')

Related

Getting two letter language code from get_current_language

I am using Django internationalization and use the get_current_language call to get the current language. However, that is a language code plus region code (e.g. en-gb), while I only want the language code (e.g. en).
How can I get just the two-letter language code?
You can simply split on the dash.
https://docs.djangoproject.com/en/1.11/topics/i18n/translation/#how-django-discovers-language-preference
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 has de available, Django uses de.
This kind of expands on #mccainz's answer.
I propose you create a custom template filter, as documented here
#register.filter
def country_only(value):
return value[0:value.find("-")]
Usage would be:
{{lang|country_only}}

Django enable date localization but not translations

I want Django to localize all dates (in all regions), but I don't want translations. It seems like for a date to be put into the right locale, we need to add its language to LANGUAGES.
For dates to be localized, we also need USE_I18N = True and USE_L10N = True.
Is this even possible?
I don't want translations, because as long as the site is not fully translated, you will have a website that is only half-translated. This is an issue due to django, because its error messages are all translated.
The best approach for you is to store your data in your database as unix timestamps and then display them using javascript. This immidiately eliminates all the complex code you have for detecting the user's locale in django. With javascript it's a lot easier to do that, and also to display the time using the appropriate format.
toLocaleDateString is your friend
The toLocaleDateString() method returns a string with a language
sensitive representation of the date portion of this date. The new
locales and options arguments let applications specify the language
whose formatting conventions should be used and allow to customize the
behavior of the function. In older implementations, which ignore the
locales and options arguments, the locale used and the form of the
string returned are entirely implementation dependent.

How to get user's preferred language in Django?

I need to know the user's preferred language—preferrably without having to parse the HTTP Accept-Language header myself. The only reason I need it is to return a list of month names localized for their preferred language in an AJAX call. My application has no other needs for internationalization.
def ajax_get_month_names(request):
# Get the user's preferred language
# Get and return the month names using Python's locale features (pretty easy)
To get a language code try this code:
from django.utils.translation import get_language_from_request
language = get_language_from_request(request)

parsing language params in widget=BootstrapDateInput()?

How to pass language params to BootstrapDateInput
What about?
widget=BootstrapDateInput(language="pt-BR")
Any ideas?
The widget uses translation.get_language() to get the current language.
If you want to force a locale, you can set it manually, e.g.:
from django.utils import translation
translation.activate('pt-BR')
widget=BootstrapDateInput()
If you only use one language, set it in your settings.py:
LANGUAGE_CODE = 'pt-br'
In django-bootstrap-toolkit's versions before 2.11.5 there was an issue with the widget, which caused the widget to always use the same language-specific JS file, instead of using the one appropriate for the current language. This means that most likely, only the language set in settings.LANGUAGE_CODE would be supported by the widget, and it would default to English otherwise.
The issue has been fixed in version 2.11.5.

Can i use an other language instead of english for default django translation

Can I use another language instead of english(say, french) for default django translation.
For example, instead for doing this:
messages.error(request, _('My message in english'))
I do this:
messages.error(request, _('Mon message en francais'))
Yeah, you could do that, and it would mostly work, but better would be to write them in English and then provide French translations (via the standard i18n approach), and to set the project's LANGUAGE_CODE to 'fr' as well.
That way, your code will be more easily reusable in other languages, and - perhaps more usefully to you if you're not worried about that - you'll be able to cleanly use French/other language translations already available in any third-party apps you want to add to your site, else you'll be mixing what Django thinks is default English (but is French) and thinks is French (and is French)
Allez! ;o)