Previous Page Next Page

Setting Language Preference

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:

  1. First, Django looks for the django_language key in the current user's session.

  2. If Django cannot find the django_language key, it looks for a cookie called django_language in the request.

  3. If Django cannot find the django_language cookie, it looks at the HTTP_ACCEPT_LANGUAGE header in the request. The browser sends this header to tell the server which language(s) the user prefers, ordered by priority. Django tries each setting in the list until it finds one that is supported.

  4. If Django cannot find a language in the header, it uses the LANGUAGE_CODE setting in the settings.py file.

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 Session

In 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:

1.
Stop the development server.

2.
Open the iFriends/settings.py file in an editor.

3.
Add the following setting to set the default language for the site to English:

LANGUAGE_CODE = 'en-us'

4.
Add the following entry to the MIDDLEWARE_CLASSES setting to enable the LocaleMiddleware framework:

'django.middleware.locale.LocaleMiddleware',

5.
Save the iFriends/settings.py file.

6.
Open the iFriends/Home/views.py file in an editor.

7.
Add the following line of code, shown in Listing 20.2, to define the siteLanguages tuple that contains language names and codes:

siteLanguages = (('en', 'English'), ('de', 'German' ))

8.
Add the following ChoiceField, shown in Listing 20.2, to add a list of languages to the LoginForm:

Language = forms.ChoiceField(choices=siteLanguages)

9.
Add the following line of code, shown in Listing 20.2, to set the django_language key in the user's session:

request.session['django_language'] = request.POST['Language']

10.
Save the iFriends/Home/views.py file.

11.
Start the development server.

12.
Access the following URL in a web browser to access the login page, shown in Figure 20.1:

http://127.0.0.1:8000/Login/

Figure 20.1. The login_user() form with a language option for the iFriends site, displaying an English login message.


The message should be in English, because the language hasn't been set for the session.

13.
Enter a valid username and password, and select German from the Language drop-down menu.

14.
Click the Login button. You should be redirected to a home page similar to the one shown in Figure 20.2. The welcome message in the upper-right corner should be in German.

Figure 20.2. The home_view() web page for the iFriends site with a German welcome message.


15.
Access the following URL again in a web browser to go to the login page:

http://127.0.0.1:8000/Login/

As shown in Figure 20.3, the message should now be in German.



Figure 20.3. The login_user() form with a language option for the iFriends site, displaying a German login message.


16.
Enter a valid username and password. This time, select English from the Language drop-down menu.

17.
Click the Login button. You should be redirected to a home page similar to the one shown in Figure 20.4. The welcome message should be in English.



Figure 20.4. The home_view() web page for the iFriends site with an English welcome message.


Listing 20.2. The LoginForm and login_user() View Function Definitions in the iFriends/Home/views.py File

siteLanguages = (('en', 'English'), ('de', 'German' ))
class LoginForm(forms.Form):
        username = forms.CharField(max_length=30)
        password = forms.CharField(max_length=20, widget=forms.PasswordInput())
        Language = forms.ChoiceField(choices=siteLanguages)

def login_user(request, next='/'):
    message = gettext('Login User')
    lForm = LoginForm()

    if request.method == 'GET':
        request.session.set_test_cookie()

    if request.method == 'POST':
        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()

            if request.GET.has_key('next'):
                next = request.GET['next']
            if request.POST['submit'] == 'Login':
                postDict = request.POST.copy()
                lForm = LoginForm(postDict)
                if lForm.is_valid():
                    uName = request.POST['username']
                    uPass = request.POST['password']
                    user = authenticate(username=uName, password=uPass)
                    if user is not None:
                        if user.is_active:
                            login(request, user)
                            request.session['django_language'] =
                            request.POST['Language']
                            return HttpResponseRedirect(next)
                        else:
                            message = 'Account Deactivated'
                    else:
                        message = 'Login Incorrect'
        else:
            message = "Please enable cookies and try again."

    return render_to_response('registration/login.html',{
                'lForm': lForm,
                'message': message})


					  


Previous Page Next Page