Search code examples
pythondjangointernationalizationtranslationdjango-i18n

Django translations does not work for html templates


The project running Django 4.1 with the settings below:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.i18n',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

LANGUAGE_CODE = 'uk'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

LOCALE_PATHS = (
    os.path.join(BASE_DIR, '/locale'),
    os.path.join(BASE_DIR, 'apps/hub/locale'),
)

LANGUAGES = (
    ('uk', _('Українська')),
    ('en', _('English')),
)

I run makemessages and compilemessages and get dajngo.po file with the following content: Two items below are from html and are not changing upon language has changed.

#: .\templates\_footer.html:14 .\templates\_header.html:12
msgid "Головна"
msgstr "Home"

#: .\templates\_footer.html:15 .\templates\_header.html:13
msgid "Про нас"
msgstr "About"

But this item below does work:

#: .\apps\hub\views.py:19
msgid "Выход"
msgstr "Exit"

All html files except base.html start with {% load i18n %}, have tags {% translate "Головна" %} Do I miss something?


Solution

  • Well, I've solved the issue. The problem was in LOCALE_PATHS

    LOCALE_PATHS = (
        os.path.join(BASE_DIR, 'locale'),  # there was a redundant /
        os.path.join(BASE_DIR, 'apps/hub/locale'),
    )
    
    print(LOCALE_PATHS) # showed me a wrong path