Skip to content

Fixed loading translations with language subtags in Select2 widget. #85

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 16 additions & 17 deletions django_select2/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,16 @@ class Select2Mixin:

empty_label = ""

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.i18n_name = SELECT2_TRANSLATIONS.get(get_language())

def build_attrs(self, base_attrs, extra_attrs=None):
"""Add select2 data attributes."""
default_attrs = {"data-minimum-input-length": 0}
default_attrs = {
"lang": self.i18n_name,
"data-minimum-input-length": 0,
}
if self.is_required:
default_attrs["data-allow-clear"] = "false"
else:
Expand All @@ -100,32 +107,28 @@ def optgroups(self, name, value, attrs=None):
self.choices = list(chain([("", "")], self.choices))
return super().optgroups(name, value, attrs=attrs)

def _get_media(self):
@property
def media(self):
"""
Construct Media as a dynamic property.

.. Note:: For more information visit
https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property
"""
lang = get_language()
select2_js = (settings.SELECT2_JS,) if settings.SELECT2_JS else ()
select2_css = (settings.SELECT2_CSS,) if settings.SELECT2_CSS else ()

i18n_name = SELECT2_TRANSLATIONS.get(lang)
if i18n_name not in settings.SELECT2_I18N_AVAILABLE_LANGUAGES:
i18n_name = None

i18n_file = (
("%s/%s.js" % (settings.SELECT2_I18N_PATH, i18n_name),) if i18n_name else ()
)
i18n_file = ()
if self.i18n_name in settings.SELECT2_I18N_AVAILABLE_LANGUAGES:
i18n_file = (
("%s/%s.js" % (settings.SELECT2_I18N_PATH, self.i18n_name),)
)

return forms.Media(
js=select2_js + i18n_file + ("django_select2/django_select2.js",),
css={"screen": select2_css + ("django_select2/django_select2.css",)},
)

media = property(_get_media)


class Select2TagMixin:
"""Mixin to add select2 tag functionality."""
Expand Down Expand Up @@ -212,11 +215,7 @@ def __init__(self, attrs=None, choices=(), **kwargs):
Value is a name of a field in a model (used in `queryset`).

"""
self.choices = choices
if attrs is not None:
self.attrs = attrs.copy()
else:
self.attrs = {}
super().__init__(attrs, choices)

self.uuid = str(uuid.uuid4())
self.field_id = signing.dumps(self.uuid)
Expand Down
13 changes: 13 additions & 0 deletions tests/test_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from collections.abc import Iterable

import pytest
from django.contrib.admin.widgets import SELECT2_TRANSLATIONS
from django.db.models import QuerySet
from django.urls import reverse
from django.utils import translation
Expand Down Expand Up @@ -46,6 +47,12 @@ def test_initial_form_class(self):
assert "my-class" in widget.render("name", None)
assert "django-select2" in widget.render("name", None)

@pytest.mark.parametrize("code,name", SELECT2_TRANSLATIONS.items())
def test_lang_attr(self, code, name):
translation.activate(code)
widget = self.widget_cls()
assert f'lang="{name}"' in widget.render("name", None)

def test_allow_clear(self, db):
required_field = self.form.fields["artist"]
assert required_field.required is True
Expand Down Expand Up @@ -219,6 +226,12 @@ def test_initial_form_class(self):
"name", None
)

@pytest.mark.parametrize("code,name", SELECT2_TRANSLATIONS.items())
def test_lang_attr(self, code, name):
translation.activate(code)
widget = self.widget_cls(data_view="heavy_data_1")
assert f'lang="{name}"' in widget.render("name", None)

def test_selected_option(self, db):
not_required_field = self.form.fields["primary_genre"]
assert not_required_field.required is False
Expand Down
1 change: 1 addition & 0 deletions tests/testapp/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
("de", "German"),
("en", "English"),
]
LANGUAGE_CODE = "en"

TEMPLATES = [
{
Expand Down