Django build in error runtime translation

Viewed 205

I want to translate Django buildin errors in different languages on runtime. Is it possible to translate django error for requested user according to his region.

2 Answers

Custom django run time language change setup Create a directory name as locale

And add this to django settings.py LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'),]

Also add this in middleware in settings.py

MIDDLEWARE = [ 
    'django.contrib.sessions.middleware.SessionMiddleware',
    # here
    'django.middleware.locale.LocaleMiddleware', 
    'django.middleware.common.CommonMiddleware',
] 

If you want ot restrict languages you can add this in settings.py

LANGUAGES = [ ('en', 'English'), ('fi', 'Finnish'), ]

Now in terminal run this

django-admin makemessages -l fi

This command will create fi directory in locale dir In this dir there is a .po file. Open it and add

msgid "your text here"
msgstr "your translation here"

And run this in terminal

django-admin compilemessages

Add ‘ln’ parameter in request header for which language you want to change like ‘en’, ‘tr’, ‘fi’

For session base user run add this in init method

from django.utils import translation
def lang(self, request, *args, **kwargs):
    ln = request.META.get('HTTP_LN')
    user_language = ln
    request.session[translation.LANGUAGE_SESSION_KEY] = user_language
    translation.activate(user_language)

And user will see translated data Note: you can only translate that string which you have added in your PO file.enter code here

Related