I am bulding an app in django, writing all interface messages in english to after translate them to other language. My first attempt is using the spanish as language target. I have been reading other questions, but I have not had success with translation in view and template. Some questions are:
- Localization doesn't work
- Django internationalization doesn't work in my project
- Django translations does not work
- Many others
In the most of them, the problem is LOCAL_PATHS
setting is bad set. However, I followed the recommendations of the answers, so I think this is not my problem and I can't figure out what it is.
These are my settings.
# Notice a LocalMiddleware
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
# I have a special directory to my templates
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True, # Still needed for admin templates
...
}
# Language settings
LANGUAGE_CODE = 'es'
LANGUAGES = [
('en', _('English')),
('es', _('Spanish')),
]
# I use BASE/DIR to configure the paths...
LOCALE_PATHS = [
BASE_DIR / 'locale',
BASE_DIR / 'utils/locale',
]
USE_I18N = True
Project structure:
In each app there are its own 'locale' directories and the tranlations inside apps work perfectly.
The messages that can't be translate are in 'utils' package. In it there are general functions and other stuffs. So, I have a 'locale' directory for 'utils' and one to my general project (for other translations outside 'utils' and apps) and that's the why these two paths are in LOCALE_PATHS
, to the apps be able to use the .mo
files of them.
I only pass the string that should be translated (self.error_message
) to the context and print it in view as test. However neither in console nor in the template the string is translated.
class SocialLoginErrorView(TemplateView):
template_name = 'user/social_login_error.html'
def get_context_data(self, **kwargs) -> dict[Any, Any]:
"""Send the error message to the template."""
self.get_params_data()
context = super().get_context_data(**kwargs)
print(f'{gettext(self.error_message)}\n{get_language()'}\n{settings.LOCALE_PATHS})
context['error_message'] = self.error_message
return context
Template social_login_error.html
:
{% extends 'base.html' %}
{% load i18n %}
{% block head_content %}
<title>Hubo un problema al iniciar sesión</title>
{% endblock head_content %}
{% block body_content %}
{% get_current_language as LANGUAGE_CODE %}
<h2>Error al iniciar sesión</h2>
<div>
<span>Se ha detectado un problema al iniciar sesión:</span>
<br/>
<span>{% translate error_message %}</span>
<br/>
HOLA
<span>{{LANGUAGE_CODE|language_name}}</span>
</div>
{% endblock body_content %}
Results: the message is still in english.
In console
And template