From 8350aae7ea5fed09f4978317c7ca4852c8bf1441 Mon Sep 17 00:00:00 2001 From: Valentin Deniaud Date: Wed, 6 Jul 2022 10:59:37 +0200 Subject: [PATCH] dataviz: support required filter without default value (#66299) --- combo/apps/dataviz/forms.py | 7 ++++++ tests/test_dataviz.py | 44 ++++++++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/combo/apps/dataviz/forms.py b/combo/apps/dataviz/forms.py index 1701de0e..ea57832f 100644 --- a/combo/apps/dataviz/forms.py +++ b/combo/apps/dataviz/forms.py @@ -204,6 +204,13 @@ class ChartNgForm(ChartFiltersMixin, forms.ModelForm): for filter_ in self.instance.available_filters: if 'default' in filter_: self.instance.filter_params[filter_['id']] = filter_['default'] + elif filter_.get('required'): + options = ( + filter_['options'][0][1] + if isinstance(filter_['options'][0], list) + else filter_['options'] + ) + self.instance.filter_params[filter_['id']] = options[0]['id'] else: for filter_ in self.instance.available_filters: if filter_['id'] in self.cleaned_data: diff --git a/tests/test_dataviz.py b/tests/test_dataviz.py index ce769b20..f27c0bdf 100644 --- a/tests/test_dataviz.py +++ b/tests/test_dataviz.py @@ -470,7 +470,16 @@ STATISTICS_LIST = { ['Category A', [{'id': 'test', 'label': 'Test'}]], ['Category B', [{'id': 'test-2', 'label': 'test 2'}]], ], - } + }, + { + "id": "cards_count", + "label": "Cards", + "options": [ + ['Category A', [{'id': 'test', 'label': 'Test'}]], + ['Category B', [{'id': 'test-2', 'label': 'test 2'}]], + ], + "required": True, + }, ], }, { @@ -500,6 +509,22 @@ STATISTICS_LIST = { }, ], }, + { + 'url': 'https://authentic.example.com/api/statistics/required-without-default/', + 'name': 'Required without default', + 'id': 'required-without-default', + "filters": [ + { + "id": "test", + "label": "Test", + "options": [ + {"id": "b", "label": "B"}, + {"id": "a", "label": "A"}, + ], + "required": True, + }, + ], + }, ] } @@ -1450,6 +1475,23 @@ def test_chartng_cell_manager_new_api(app, admin_user, new_api_statistics): assert resp.pyquery('optgroup[label="Category A"] option').val() == 'test' assert resp.pyquery('optgroup[label="Category B"] option').val() == 'test-2' + assert resp.form[field_prefix + 'cards_count'].options == [ + ('test', True, 'Test'), + ('test-2', False, 'test 2'), + ] + cell.refresh_from_db() + assert cell.filter_params == {'cards_count': 'test'} + + required_without_default_stat = Statistic.objects.get(slug='required-without-default') + resp.form[field_prefix + 'statistic'] = required_without_default_stat.pk + manager_submit_cell(resp.form) + assert resp.form[field_prefix + 'test'].options == [ + ('b', True, 'B'), + ('a', False, 'A'), + ] + cell.refresh_from_db() + assert cell.filter_params == {'test': 'b'} + deprecated_stat = Statistic.objects.get(slug='deprecated-filter') resp.form[field_prefix + 'statistic'] = deprecated_stat.pk manager_submit_cell(resp.form) -- 2.30.2