5

Following Translating URL patterns, I can make my urls being prefixed with the active language, but I can't get them translated.

urls.py

from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.utils.translation import ugettext_lazy as _

from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings

from exercises.views import ExerciseListView

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
]

urlpatterns += i18n_patterns(
   ...
   url(_(r'^exercises/$'), ExerciseListView.as_view(), name='list'),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

locale/es/LC_MESSAGES/django.po

#: myproject/urls.py:54
msgid "^exercises/$"
msgstr "^ejercicios/$"

manage.py shell

>>> from django.core.urlresolvers import reverse
>>> from django.utils.translation import activate
>>> activate('en')
>>> reverse('list')
'/en/exercises/'
>>> activate('es')
>>> reverse('list')
'/es/exercises/'          <---- should be /es/ejercicios as translated in .po

How can I make reverse('list') display '/es/ejercicios/' ?

frlan
  • 6,950
  • 3
  • 31
  • 72
marcanuy
  • 23,118
  • 9
  • 64
  • 113

2 Answers2

3

The problem were not only the URL's but also all the translation strings from the message file weren't being translated.

Having the following directory structure:

-Project  #base directory
  -apps
  -templates
  -project
     -settings.py
  -locale
     -es
       -LC_MESSAGES
          -django.po

Just adding the LOCALE_PATHS config to settings.py fix the problem

LOCALE_PATHS = (
    'locale',
)

Django will look within each of these paths for the /LC_MESSAGES directories containing the actual translation files.

*Tested in Django 1.8

marcanuy
  • 23,118
  • 9
  • 64
  • 113
  • 2
    To anyone else reading this and thinking "nah, that can't be it, I'm seeing some translated strings in my templates, so obviously everything is configured?" ... no. You really need to add this. Even though PARTS of your translations will show up. I wish I hadn't ignored this answer two hours ago. Django 3.1, by the way. – maligree Mar 22 '21 at 12:26
  • 1
    Django 3.1.8, the same problem! Saved my day! – shaheen g Oct 21 '21 at 16:16
0

I had the same problem, and the solution was, in my settings.py, making match my LANGUAGE_CODE with the first language in LANGUAGES list:

# In my settings.py
LANGUAGE_CODE = 'en'

LANGUAGES = (
    ('en', _('English')),
    ('es', _('Spanish')),
)
2ehr
  • 128
  • 1
  • 7