Site icon Tutorial

How Django Discovers Language Preference

Once you’ve prepared your translations – or, if you just want to use the translations that come with Django – you’ll need to activate translation for your app.

Behind the scenes, Django has a very flexible model of deciding which language should be used – installation-wide, for a particular user, or both.

To set an installation-wide language preference, set LANGUAGE_CODE. Django uses this language as the default translation – the final attempt if no better matching translation is found through one of the methods employed by the locale middleware.

If all you want is to run Django with your native language all you need to do is set LANGUAGE_CODE and make sure the corresponding message files and their compiled versions (.mo) exist.

If you want to let each individual user specify which language they prefer, then you also need to use the LocaleMiddleware. LocaleMiddleware enables language selection based on data from the request. It customizes content for each user.

To use LocaleMiddleware, add ‘django.middleware.locale.LocaleMiddleware’ to your MIDDLEWARE_CLASSES setting. Because middleware order matters, you should follow these guidelines:

MIDDLEWARE_CLASSES = [
‘django.contrib.sessions.middleware.SessionMiddleware’,
‘django.middleware.locale.LocaleMiddleware’,
‘django.middleware.common.CommonMiddleware’,
]

LocaleMiddleware tries to determine the user’s language preference by following this algorithm:

LANGUAGES = [
(‘de’, _(‘German’)),
(‘en’, _(‘English’)),
]

This example restricts languages that are available for automatic selection to German and English (and any sublanguage, like de-ch or en-us).

from django.utils.translation import ugettext_lazy as _

LANGUAGES = [
(‘de’, _(‘German’)),
(‘en’, _(‘English’)),
]

Once LocaleMiddleware determines the user’s preference, it makes this preference available as request.LANGUAGE_CODE for each HttpRequest. Feel free to read this value in your view code. Here’s a simple example:

from django.http import HttpResponse

def hello_world(request, count):
if request.LANGUAGE_CODE == ‘de-at’:
return HttpResponse(“You prefer to read Austrian German.”)
else:
return HttpResponse(“You prefer to read another language.”)

Note that, with static (middleware-less) translation, the language is in settings.LANGUAGE_CODE, while with dynamic (middleware) translation, it’s in request.LANGUAGE_CODE.

Back to Tutorial

Exit mobile version