Skip to content

Commit 496cc7c

Browse files
dzhuangcodingjoe
authored andcommitted
Fallback i18n js files for zh-hans/zh-hant. (#468)
* Fallback i18n js files for zh-hans/zh-hant. * Use Django admin's built-in SELECT2_TRANSLATIONS to determine the lang of i18n js files.
1 parent 17af750 commit 496cc7c

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

django_select2/forms.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -98,12 +98,23 @@ def _get_media(self):
9898
.. Note:: For more information visit
9999
https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property
100100
"""
101+
lang = get_language()
102+
i18n_name = None
101103
try:
102-
# get_language() will always return a lower case language code, where some files are named upper case.
103-
i = [x.lower() for x in settings.SELECT2_I18N_AVAILABLE_LANGUAGES].index(get_language())
104-
i18n_file = ('%s/%s.js' % (settings.SELECT2_I18N_PATH, settings.SELECT2_I18N_AVAILABLE_LANGUAGES[i]), )
105-
except ValueError:
106-
i18n_file = ()
104+
from django.contrib.admin.widgets import SELECT2_TRANSLATIONS
105+
i18n_name = SELECT2_TRANSLATIONS.get(lang)
106+
if i18n_name not in settings.SELECT2_I18N_AVAILABLE_LANGUAGES:
107+
i18n_name = None
108+
except ImportError:
109+
# TODO: select2 widget feature needs to be backported into Django 1.11
110+
try:
111+
i = [x.lower() for x in settings.SELECT2_I18N_AVAILABLE_LANGUAGES].index(lang)
112+
i18n_name = settings.SELECT2_I18N_AVAILABLE_LANGUAGES[i]
113+
except ValueError:
114+
pass
115+
116+
i18n_file = ('%s/%s.js' % (settings.SELECT2_I18N_PATH, i18n_name),) if i18n_name else ()
117+
107118
return forms.Media(
108119
js=(settings.SELECT2_JS,) + i18n_file + ('django_select2/django_select2.js',),
109120
css={'screen': (settings.SELECT2_CSS,)}

tests/test_forms.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,13 +129,22 @@ def test_i18n(self):
129129
'django_select2/django_select2.js'
130130
)
131131

132-
translation.activate('zh-cn')
132+
pytest.importorskip("django", minversion="2.0.4")
133+
134+
translation.activate('zh-hans')
133135
assert tuple(Select2Widget().media._js) == (
134136
'//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js',
135137
'//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/i18n/zh-CN.js',
136138
'django_select2/django_select2.js'
137139
)
138140

141+
translation.activate('zh-hant')
142+
assert tuple(Select2Widget().media._js) == (
143+
'//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js',
144+
'//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/i18n/zh-TW.js',
145+
'django_select2/django_select2.js'
146+
)
147+
139148

140149
class TestSelect2MixinSettings(object):
141150
def test_default_media(self):

0 commit comments

Comments
 (0)