Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest framework how to internationalize fields

I have followed the Django documentation for setting up internationalization.

I require to return a translation of various choices fields depending on the language requested.

For example I have the following choices fields;

CHOICE_TYPES = (('short', _('Short Term')),('long', _('Long Term')), ('mixed', _('Mixed')),)

I have setup my Locale and .po files as per the documentation. For example;

msgid "Short Term"
msgstr "단기계약"

I am requesting the language using the Accept-Language header on a request.

But it seems that Django is not seeing the locale or there is another step I haven't undertaken for DRF.

Django does see the language request as I am using django-hvad for model translations and they are returned correctly.

Any help would be appreciated.

Edit: Added relevant code extracts

Settings.py

LANGUAGES = [
    ('en', _('English')),
    ('ja', _('Japanese')),
]

LANGUAGE_CODE = 'en-us'

USE_I18N = True
USE_L10N = True

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.locale.LocaleMiddleware',
]

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

# replicated locale folder in 3 locations as I thought Django couldn't find it 
LOCALE_PATHS = (
    '../locale',
    '<full_path>locale',
    '<full_path>/<app_name>/locale',
)

models.py

from django.utils.translation import ugettext_lazy as _

CHOICES = (('short', _('Short Term')),('long', _('Long Term')), ('mixed', _('Mixed')),)

# In the relevant model/s
term = models.CharField(max_length=10, choices=CHOICES, default='short')

serializers.py

class SomethingSerializer(TranslatableModelSerializer):
    class Meta:
        depth = 1
        model = Something
        fields = (...., ...., 'term')

In locale/ja/LC_MESSAGES

django.po

msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"Language: ja\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"X-Translated-Using: django-rosetta 0.7.12\n"

#: common/models.py:8
msgid "Short Term"
msgstr "test translation"

And finally I've ran commands as follows;

$ ./manage.py makemessages -l ja
processing locale ja
$ ./manage.py compilemessages -l ja
processing file django.po in /<Path>/locale/ja/LC_MESSAGES
processing file django.po in /<Path>/locale/ja/LC_MESSAGES
processing file django.po in /<Path>/<App Name>/locale/ja/LC_MESSAGES
like image 470
daesu Avatar asked Dec 12 '25 21:12

daesu


1 Answers

Silliness on my part. It was translating fine, I just wasn't calling it correctly in the serializer.

In my serializer I had;

class SomethingSerializer(TranslatableModelSerializer):
    class Meta:
        depth = 1
        model = Something
        fields = (...., ...., 'term')

Whereas I should have been requesting the display name for 'term' as follows;

class SomethingSerializer(TranslatableModelSerializer):
    term = serializers.SerializerMethodField()
    class Meta:
        depth = 1
        model = Something
        fields = (...., ...., 'term')

  def get_term(self,obj):
    return obj.get_term_display()
like image 156
daesu Avatar answered Dec 14 '25 13:12

daesu