[Django]-Set language within a django view

99πŸ‘

βœ…

To quote parts from Django’s Locale Middleware (django.middleware.locale.LocaleMiddleware):

from django.utils import translation

class LocaleMiddleware(object):
    """
    This is a very simple middleware that parses a request
    and decides what translation object to install in the current
    thread context. This allows pages to be dynamically
    translated to the language the user desires (if the language
    is available, of course).
    """

    def process_request(self, request):
        language = translation.get_language_from_request(request)
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language()

The translation.activate(language) is the important bit.

πŸ‘€stefanw

15πŸ‘

Be sure to also add deactivate in process_response, otherwise you will have problems with different threads.

from django.utils import translation

class LocaleMiddleware(object):
    """
    This is a very simple middleware that parses a request
    and decides what translation object to install in the current
    thread context. This allows pages to be dynamically
    translated to the language the user desires (if the language
    is available, of course).
    """

    def process_request(self, request):
        language = translation.get_language_from_request(request)
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language()

    def process_response(self, request, response):
        translation.deactivate()
        return response
πŸ‘€webjunkie

7πŸ‘

If just want to get the translated strings for a language for whatever reason, you can use override as a decorator like this:

from django.utils import translation
from django.utils.translation import ugettext as _

with translation.override(language):
    welcome = _('welcome')
πŸ‘€Flimm

5πŸ‘

You can consider storing the language in the user model and use this custom middleware django-user-language-middleware.

This allows easy translation of your Django app by looking at the selected language in the user.language field and you can always know the language preference of any user.

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.

3πŸ‘

Sometimes you want to enforce a certain language for a given view but let the browser language settings choice the language for the rest of the views. I haven’t figured out how to change the language in the view code but you can do this by implementing a simple Middleware

lang_based_on_url_middleware.py:

from django.utils import translation

# Dictionary of urls that should use special language regardless of language set in browser
#   key = url
#   val = language code
special_cases = {
    '/this/is/some/url/' : 'dk',
    '/his/is/another/special/case' : 'de',
                 }

class LangBasedOnUrlMiddleware(object):
    def process_request(self, request):
        if request.path_info in special_cases:
            lang = special_cases[request.path_info]
            translation.activate(lang)
            request.LANGUAGE_CODE = lang

In settings.py:

MIDDLEWARE_CLASSES = (
    ...
    'django.middleware.locale.LocaleMiddleware',
    'inner.lang_based_on_url_middleware.LangBasedOnUrlMiddleware', # remember that the order of LocaleMiddleware and LangBasedOnUrlMiddleware matters
    ...
)

Not an elegant solution but it works.

πŸ‘€Helgi Borg

3πŸ‘

If you are using django 1.10 or higher, there’s a new syntax for custom middleware:

from django.utils import translation

class LocaleMiddleware(object):

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        language_code = 'en' #TODO, your logic

        translation.activate(language_code)

        response = self.get_response(request)

        translation.deactivate()

        return response
πŸ‘€Patrik Beck

2πŸ‘

request.LANGUAGE_CODE if LocaleMiddleware activated.

πŸ‘€DenisKolodin

0πŸ‘

With class based views, this should work:

class YourView(SomeBuiltInView):
def get(self, request, *args, **kwargs):
    setattr(request, 'LANGUAGE_CODE', 'YOUR_LANGUAGE_CODE')
    return super().get(self, request, *args, **kwargs)

Basically all you do is make the view renderer think that the request came from YOUR_LANGUAGE_CODE rather than what was originally true.

πŸ‘€emihir0

Leave a comment