0

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:

  1. Localization doesn't work
  2. Django internationalization doesn't work in my project
  3. Django translations does not work
  4. 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:

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

Message not translated in console

And template

Message not translated in template

Jony_23
  • 322
  • 4
  • 12
  • Did you add `utils` to `INSTALLED_APPS` inside `settings.py`? – Nechoj Apr 23 '22 at 20:25
  • But `utils` is not an django app, just a package with python modules. Do I have to add a package to installed apps to could be translate the strings? – Jony_23 Apr 23 '22 at 20:29
  • Not sure, but this is what I would try next – Nechoj Apr 23 '22 at 20:31
  • Yeah, I have just tried it, but it didn't work. Even so thanks. – Jony_23 Apr 23 '22 at 21:08
  • Your syntax for combining paths is strange: `BASE_DIR / 'locale'`. I think that you should do it like `os.path.join(BASE_DIR, 'locale')`. Also for TEMPLATES. – Nechoj Apr 24 '22 at 07:48
  • I will try your advice, thanks. However, I learnt django the last year with new versions and in official documentation use the same way to fix paths. Check this [How to override templates](https://docs.djangoproject.com/en/4.0/howto/overriding-templates/). – Jony_23 Apr 24 '22 at 20:49

0 Answers0