Languages can be set at either the site level or session level. The best way to understand how language preferences work is to understand how Django determines the language preference.
Django looks in the following four places to find the language preference:
If Django cannot find the django_language key, it looks for a cookie called django_language in the request.
To set the language at the site level, all you need to do is add the LANGUAGE_CODE setting to the settings.py file. For example, to set the site language to Spanish, you would use the following setting:
LANGUAGE_CODE = 'es'
If you want to set the language on a per-user basis, you must enable the django.middleware.locale.LocaleMiddleware framework. The LocaleMiddleware framework provides access to the language settings in the session, cookies, and HTTP headers. To enable the LocaleMiddleware framework, add the following entry to the MIDDLEWARE_CLASSES setting in the settings.py file:
'django.middleware.locale.LocaleMiddleware',
Watch Out!
The LocaleMiddleware framework needs to be installed after SessionMiddleware, but before any other django.middleware frameworks.
After the LocaleMiddleware framework is enabled, your view functions and templates try to determine the language settings for each user in the session, cookies, and HTTP headers.
You can allow the user's browser to specify the preferred language, or you can set the language in the user's session. The language can be set for the user either in the session or by setting a cookie in the user's browser.
The best place to set the language is in the session, because that is the first place the LocaleMiddleware framework looks. For example, the following code sets the language for the session to English. As long as the session is active, the language is English:
def myView(request): request.session['django_language'] = 'en'
Try It Yourself: Set Language Preference in a SessionIn this section, you will enable the LocaleMiddleware framework. Then you will modify the login_user() function to allow the user to set his or her preferred language. You will modify the LoginForm to add a language choice field that you can use to set the django_language key in the user's session. Follow these steps to make the changes:
Listing 20.2. The LoginForm and login_user() View Function Definitions in the iFriends/Home/views.py File
|