- Author:
- agusmakmun
- Posted:
- March 8, 2020
- Language:
- Python
- Version:
- Not specified
- 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
- Template tag - list punctuation for a list of items by shapiromatron 9 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.