Login

Django Language Middleware

Author:
agusmakmun
Posted:
March 8, 2020
Language:
Python
Version:
Not specified
Tags:
middleware django session localization translation django-session
Score:
0 (after 0 ratings)

This example below to setup default language code as id (Indonesian).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# -*- coding: utf-8 -*-

from django.conf import settings
from django.utils import translation
from django.utils.deprecation import MiddlewareMixin
from django.utils.translation import ugettext_lazy as _


class LanguageMiddleware(MiddlewareMixin):

    def process_request(self, request):
        """
        function to activate the translation
        """
        if 'lang' in request.GET:
            language = request.GET.get('lang', 'id')
            if language in dict(settings.LANGUAGES).keys():
                request.session['_language'] = language

        language = request.session.get('_language', 'id')
        translation.activate(language)



# In your settings.py
"""
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.locale.LocaleMiddleware',

    # custom middleware
    'yourproject.middleware.LanguageMiddleware',
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGES = (
    ('id', 'Indonesia'),
    ('en', 'English')
)
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'locale'),
)
DEFAULT_LANGUAGE = 1
LANGUAGE_CODE = 'id'
USE_I18N = True
USE_L10N = True
"""

More like this

  1. Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 6 months ago
  2. Crispy Form by sourabhsinha396 7 months ago
  3. ReadOnlySelect by mkoistinen 7 months, 1 week ago
  4. Verify events sent to your webhook endpoints by santos22 8 months, 1 week ago
  5. Django Language Middleware by agusmakmun 8 months, 2 weeks ago

Comments

Please login first before commenting.