How to get current language in django?

How can I get the current language in the current thread in the model or in the administrator?

+56
python django internationalization
Jul 28 '10 at 20:01
source share
5 answers

Functions of particular interest are django.utils.translation.get_language() , which returns the language used in the current thread. See the documentation .

+93
Jul 28 '10 at 20:19
source share

Or you can also get it in your submissions.

  request.LANGUAGE_CODE 
+67
Jul 29 '10 at 6:11
source share

Be careful with the method you use to get the language . Depending on the method, Django will use different methods and information to determine the correct language to use.

When using the django.utils.translation.get_language() function, it is associated with the thread language. Prior to Django 1.8, it always returned settings.LANGUAGE_CODE when translations were disabled. If you want to manually redefine the language of the streams, you can use the override() or activate() functions, which are not explicitly specified explicitly, but well, still useful:

 from django.utils import translation with translation.override('fr'): print(_("Hello")) # <= will be translated inside the with block translation.activate('fr') # <= will change the language for the whole thread. # You then have to manually "restore" the language with another activate() translation.activate('en') # <= change languages manually 

If you want django to check the path and / or request (language cookie, ...) , which is much more common, for example. www.example.com/en/<somepath> vs www.example.com/fr/<somepath> , use django.utils.translation.get_language_from_request(request, check_path=False) . In addition, it will always return a valid language in settings.LANGUAGES

It was not easy for me to find these differences through Google on this subject, so here for further links.

+21
Nov 11 '15 at 11:04
source share

Just add that if you use django.utils.translation.get_language() , then you should keep in mind that if this section of code is called asynchronously (for example, as a celery task), this approach will not work because of its work to another thread.

+7
Oct 30 '13 at 11:05
source share

You can read the locale system for language information.

0
Jul 28 '10 at 20:04 on
source share



All Articles