Search code examples
pythondjangodjango-i18n

Django Internationalization (I18N) not changing text


I created an simple website to test internationalization, but I can't make it work the way I wanted. I would like to change messages in my views.py without checking the request.LANGUAGE_CODE (which is showing correctly).

I can go to the urls with prefix /en/ and /pt-br/ but they don't change the text in the template.

I tried running

django-admin makemessages --locale=pt_BR

I changed the lines

#: mytest/views.py:7
msgid "Welcome to my site."
msgstr "Bem vindo ao meu site."

ran

django-admin compilemessages --locale=pt_BR

PS: (even though it is wrong, I tried django-admin makemessages/compilemessages --locale=pt-br as well)

What I changed in settings.py (added my app, added locale middleware, added some internalization settings)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'mytest'
]
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LOCALE_PATHS = [
    os.path.join(BASE_DIR, 'locale/translations/'),
]

LANGUAGE_CODE = 'en-us'

from django.utils.translation import ugettext_lazy as _
LANGUAGES = [
  ('pt-br', _('Portuguese')),
  ('en', _('English')),
]

TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

views.py

from django.shortcuts import render
from django.utils.translation import ugettext_lazy as _

def index(request):
    print(request.LANGUAGE_CODE) #this shows correctly the prefix in the url
    output = _("Welcome to my site.")
    context = {"test_translate": output}
    return render(request, "mytest/index.html", context)

urls.py

from django.conf.urls.i18n import i18n_patterns
from mytest import views

urlpatterns = [
]
urlpatterns += i18n_patterns(
    url(r'^$', views.index, name='index'),
)

Solution

  • I think my path was not correct. I believe the extra slash was wrong... I deleted /translations/ from the LOCALE_PATH and it is working now.

    LOCALE_PATHS = [
        os.path.join(BASE_DIR, 'locale'),
    ]
    

    Then I run

    django-admin compilemessages -l pt_BR
    

    Modify the *.po generated and run

    django-admin compilemessages -l pt_BR
    

    I also renamed en-us to en in LANGUAGE_CODE = 'en-us'