From 752de0d9c0e358c018ee5a9009567243a9d64831 Mon Sep 17 00:00:00 2001 From: thatmattlove Date: Tue, 7 Sep 2021 18:30:45 -0700 Subject: [PATCH] Fixes #7205: Handle `null_option` when getting selected form values in `applied_filters` template tag --- docs/release-notes/version-3.0.md | 1 + netbox/utilities/forms/utils.py | 13 +++++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/release-notes/version-3.0.md b/docs/release-notes/version-3.0.md index e1bb57d72..f1b96d8b3 100644 --- a/docs/release-notes/version-3.0.md +++ b/docs/release-notes/version-3.0.md @@ -10,6 +10,7 @@ * [#7176](https://github.com/netbox-community/netbox/issues/7176) - Fix issue where query parameters were duplicated across different forms of the same type * [#7188](https://github.com/netbox-community/netbox/issues/7188) - Fix issue where select fields with `null_option` did not render or send the null option * [#7193](https://github.com/netbox-community/netbox/issues/7193) - Fix prefix (flat) template issue when viewing child prefixes with prefixes available +* [#7205](https://github.com/netbox-community/netbox/issues/7205) - Fix issue where selected fields with `null_option` set were not added to applied filters --- diff --git a/netbox/utilities/forms/utils.py b/netbox/utilities/forms/utils.py index 0121b250c..c0c14c80d 100644 --- a/netbox/utilities/forms/utils.py +++ b/netbox/utilities/forms/utils.py @@ -120,11 +120,20 @@ def get_selected_values(form, field_name): if not hasattr(form, 'cleaned_data'): form.is_valid() filter_data = form.cleaned_data.get(field_name) + field = form.fields[field_name] # Selection field - if hasattr(form.fields[field_name], 'choices'): + if hasattr(field, 'choices'): try: - choices = dict(unpack_grouped_choices(form.fields[field_name].choices)) + grouped_choices = [(k, v) for k, v in field.choices] + + if hasattr(field, 'null_option'): + # If the field has a `null_option` attribute set and it is selected, + # add it to the field's grouped choices. + if field.null_option is not None and field.null_option in filter_data: + grouped_choices.append((field.null_option, field.null_option)) + + choices = dict(unpack_grouped_choices(grouped_choices)) return [ label for value, label in choices.items() if str(value) in filter_data ]