Django i18n cannot use translated text in a dict

26 Views Asked by At

I am unable to store the translated texts in a dict

class TestAPIView(APIView):

    def get(self, request):
        return Response({'msg': _("My error msg")})

The code above works. However when I tried to put the text into a dict.

msg = {
   123 : _("My error msg")
}

class TestAPIView(APIView):

    def get(self, request):
        return Response({'msg': msg[123]})

This doesn't translated the text. I have tried rerunning the makemessages and compilemessages, but it doesn't help.

Any help?

1

There are 1 best solutions below

0
willeM_ Van Onsem On

You need to work with gettext_lazy(…) [Django-doc], not gettext(…) [Django-doc] to prevent translating the string "prematurely":

from django.utils.translation import gettext_lazy as _

msg = {123: _('My error msg')}


class TestAPIView(APIView):
    def get(self, request):
        return Response({'msg': msg[123]})