How to make Django respect locale when accessing localflavor?

37 Views Asked by At

I'm trying to apply multi-language support to a Django application, and I have the basic configuration working so I can set a language session key and automatically pull the correct translations for the each gettext call around all my field labels.

However, I have some Ajax calls that populate fields for country/state/province names, pulling data from the django-localflavor package, which includes full translation support.

However, when I return, say, localflavor.jp.jp_prefectures.JP_PREFECTURES in my JSON response, even though my language session key is set to Japanese, and the values in that dictionary are wrapped with gettext, the values returned are in English, not Japanese.

My Ajax view looks something like:

from localflavor.jp.jp_prefectures import JP_PREFECTURES

def get_country_states(request):
    lang = request.session.get('l', 'en')
    code = request.GET.get('code')
    if code == 'ja':
        states = {k: str(v) for k, v in JP_PREFECTURES}
    elif code == ...
        handle other cases
    return HttpResponse(json.dumps({'states': states}))

How do I ensure str(v) renders the correct translated value based on the current language l session setting? I thought this happened automatically?

Even though the values in JP_PREFECTURES are gettext instances, if I try and return them directly in the JSON response, I get the error:

Object of type __proxy__ is not JSON serializable

I tried this solution by doing:

from django.utils import translation

def get_country_states(request):
    lang = request.session.get('l', 'en')
    code = request.GET.get('code')
    if code == 'ja':
        with translation.override('ja'):
            states = {k: translation.gettext(v) for k, v in JP_PREFECTURES}
    elif code == ...
        handle other cases
    return HttpResponse(json.dumps({'states': states}))

but that had no effect. It still renders everything in English.

0

There are 0 best solutions below