From 4f27b9b63db60cb35cf5b92f6726937191270f13 Mon Sep 17 00:00:00 2001 From: Oskar Hahn Date: Fri, 16 Jan 2015 16:36:29 +0100 Subject: [PATCH] Fix LocalizedModelMultipleChoiceField It has to be a generator, so it does not call the queryset --- openslides/utils/forms.py | 14 ++++++++++---- tests/utils/test_forms.py | 12 ++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) create mode 100644 tests/utils/test_forms.py diff --git a/openslides/utils/forms.py b/openslides/utils/forms.py index 5013500fa..11cda07d0 100644 --- a/openslides/utils/forms.py +++ b/openslides/utils/forms.py @@ -52,19 +52,25 @@ class LocalizedModelChoiceField(forms.ModelChoiceField): class LocalizedModelMultipleChoiceField(forms.ModelMultipleChoiceField): + """ + FormField to translate models in many to many fields in forms. + """ + def __init__(self, *args, **kwargs): self.to_field_name = kwargs.get('to_field_name', None) super(LocalizedModelMultipleChoiceField, self).__init__(*args, **kwargs) def _localized_get_choices(self): + """ + Generator which calles super() and yields the values. + """ if hasattr(self, '_choices'): return self._choices - c = [] - for (id, text) in super(LocalizedModelMultipleChoiceField, self)._get_choices(): + for (id, text) in super()._get_choices(): + # This line is only required to translate permission objects text = text.split(' | ')[-1] - c.append((id, ugettext_lazy(text))) - return c + yield (id, ugettext_lazy(text)) choices = property(_localized_get_choices, forms.ChoiceField._set_choices) diff --git a/tests/utils/test_forms.py b/tests/utils/test_forms.py new file mode 100644 index 000000000..ee94c0e23 --- /dev/null +++ b/tests/utils/test_forms.py @@ -0,0 +1,12 @@ +from types import GeneratorType +from unittest.mock import MagicMock + +from openslides.utils.forms import LocalizedModelMultipleChoiceField +from openslides.utils.test import TestCase + + +class TestLocalizedModelMultipleChoiceField(TestCase): + def test_localized_get_choices(self): + test_field = LocalizedModelMultipleChoiceField(queryset=MagicMock()) + + self.assertEqual(type(test_field.choices), GeneratorType)