Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Display current locale in a template

I need to embed the current locale in a Django template's output (as part of a URL to be precise). I know that I can access the current language as {{ LANGUAGE_CODE }} if I { load i18n } but is there a similar way to access the current locale?

I suppose I could use to_locale() in the view logic and put it in the context for the template, but I'm looking for something more generic that might be part of the Django framework itself. Is there such a syntax?

like image 841
urig Avatar asked Jun 15 '11 17:06

urig


People also ask

How do I get current language in Django?

get_language() which returns the language used in the current thread. See documentation. Caveat: Returns None if translations are temporarily deactivated (by deactivate_all() or when None is passed to override()). Before Django 1.8, get_language() always returned LANGUAGE_CODE when translations were deactivated.

What is USE_L10N in Django?

The formatting system is disabled by default. To enable it, it's necessary to set USE_L10N = True in your settings file. Note. To enable number formatting with thousand separators, it is necessary to set USE_THOUSAND_SEPARATOR = True in your settings file.

How do I change the default language in Django?

Default language strings are not stored in po/mo files, they go directly in code and templates - seems that you have this right. You can switch back to it, by setting the session variable django_language back to dutch. This made it work for me, thanks a lot.


2 Answers

You might want to write your own context processor, which would call to_locale and automatically populate the context with the result -- it would just be something like this.

from django.utils.translation import to_locale, get_language def locale(request):     return {'LOCALE': to_locale(get_language())} 
like image 30
Ismail Badawi Avatar answered Sep 20 '22 13:09

Ismail Badawi


I solved this by including code below in the template

{% load i18n %} {% get_current_language as LANGUAGE_CODE %} 

and the variable LANGUAGE_CODE has the value you want (see also django docs for an example usage).

like image 155
Juan Pablo Gaviria Avatar answered Sep 19 '22 13:09

Juan Pablo Gaviria