Create a new middleware

from django.utils.translation import activate
from django.conf import settings

<pre>
class CustomLanguageMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Read the language preference from the local storage cookie
        language_preference = request.COOKIES.get('language_preference', 
None) # Instead of `None` set your default language code in case of there 
is no language_preference comes with cookies

        # If a language preference is found, set the 'Accept-Language' 
header
        if language_preference and language_preference in 
dict(settings.LANGUAGES):
            request.META['HTTP_ACCEPT_LANGUAGE'] = language_preference

        # Call the next middleware or view
        response = self.get_response(request)

        # If you want, you can also update the 'language' in the session
        if language_preference and language_preference in 
dict(settings.LANGUAGES):
            activate(language_preference)

        return response
</pre>

add it right before `django.middleware.locale.LocaleMiddleware` 

DJANGO_MIDDLEWARES = [
    # add your custom middleware here
    'django.middleware.locale.LocaleMiddleware',
]

this custom middleware will override the default behavior of the 
LocalMiddleware.

Finally, you can store the language preference in the local storage cookie:

<pre>
const languagePreference = 'ru-RU'; // Replace this with the user's 
preferred language
localStorage.setItem('language_preference', languagePreference);
</pre>

On Friday, June 20, 2014 at 7:22:53 PM UTC+6 Tom Evans wrote:

> On Fri, Jun 20, 2014 at 1:47 PM, Vernon D. Cole <verno...@gmail.com> 
> wrote:
> > (*cough*)
> > Excuse me, everyone, but many of the locale names mentioned in this
> > discussion have been invalid.
> >
> > https://docs.djangoproject.com/en/1.6/topics/i18n/#term-locale-name 
> says:
> >>
> >> locale nameA locale name, either a language specification of the form ll
> >> or a combined language and country specification of the form ll_CC.
> >> Examples: it, de_AT, es, pt_BR. The language part is always in lower 
> case
> >> and the country part in upper case. The separator is an underscore.
> >
> >
> > so 'en-gb' should not be recognized.
> > 'en_GB' ought to be.
> >
>
> What is and what is not a locale name has little bearing on what is
> accepted and returned by django.utils.translation.{set,get}_language,
> which is self-evidently a language name.
>
> Language names map to locales.
>
> Cheers
>
> Tom
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9e7717e6-7a63-48b3-9637-93b42c8f9349n%40googlegroups.com.

Reply via email to