[Django]-Saving user preferred language and django-localeurl

2👍

I ended using Django-dev (1.4), it has i18n urls built in, so no need of localeurl.

2👍

Read the following article.

http://barseghyanartur.blogspot.nl/2013/09/make-django-localeurl-rembember-your.html

In short, it’s possible with one of the last commit to the django-localeurl main branch and some tricks.

Step 1. Install django-localeurl from source (bitbucket) or pick a later commit from same place.

$ pip install hg+https://bitbucket.org/carljm/django-localeurl@764caf7a412d77aca8cc929988f333ee808719e6#egg=django-localeurl

Step 2. Update your django settings.py as follows.

Middleware classes should look as follows (order is critical).

Note, that django’s SessionMiddleware comes as first! And LocaleURLMiddleware should come before the django’s CommonMiddleware!

Note, that LOCALEURL_USE_SESSION is new.

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'localeurl.middleware.LocaleURLMiddleware',
    'django.middleware.common.CommonMiddleware',
    # ... the rest
)

LOCALEURL_USE_SESSION = True

Step 3. Direct your language switcher (POST) to the {% url ‘localeurl_change_locale’ %} view, having provided the language chosen as a locale param.

That’s pretty much it. See the article for tips to include it in your template.

0👍

django-cms does this using middleware. For inspiration, look at the class MultilingualURLMiddleware here:

https://github.com/divio/django-cms/blob/develop/cms/middleware/multilingual.py

It does the following:

  1. Look in the first part of the URL. If it matches your SUPPORTED languages (ie. settings.LANGUAGES), then call translation.activate(language) with that language code.
  2. If not, then try to see if request.session.get(“django_language”, “”) is set.
  3. If not, then try to see if request.COOKIES.get(“django_language”, “”) is set.

But what I would actually recommend is that you start using django-cms 😉

0👍

The translation of a Django app with the preferred language selected by a registered user can be done with the middleware django-user-language-middleware. This allows easy localization of your Django app by looking at the selected language in the user.language field.

Usage:

  1. Add a language field to your user model:

    class User(auth_base.AbstractBaseUser, auth.PermissionsMixin):
        # ...
        language = models.CharField(max_length=10,
                                    choices=settings.LANGUAGES,
                                    default=settings.LANGUAGE_CODE)
    
  2. Install the middleware from pip:

    pip install django-user-language-middleware

  3. Add it to your middleware class list in settings to listen to requests:

    MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
        ...
        'user_language_middleware.UserLanguageMiddleware',
        ...
    ]
    

I hope this may help people landing on this question in the future.

Leave a comment