From 1d7a7e2d1d0aade580c3bb90db309e06f0491e05 Mon Sep 17 00:00:00 2001 From: Jeremy Stretch Date: Tue, 15 Jan 2019 11:26:41 -0500 Subject: [PATCH] Fixes #2779: Include "none" option when filter IP addresses by role --- CHANGELOG.md | 1 + netbox/ipam/forms.py | 1 + netbox/utilities/forms.py | 25 ++++++++++++++++++++----- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2cd8d314a..3b356cc46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ v2.5.4 (FUTURE) ## Bug Fixes +* [#2779](https://github.com/digitalocean/netbox/issues/2779) - Include "none" option when filter IP addresses by role * [#2783](https://github.com/digitalocean/netbox/issues/2783) - Fix AttributeError exception when attempting to delete region(s) --- diff --git a/netbox/ipam/forms.py b/netbox/ipam/forms.py index b6209f5df..26d64d9b3 100644 --- a/netbox/ipam/forms.py +++ b/netbox/ipam/forms.py @@ -913,6 +913,7 @@ class IPAddressFilterForm(BootstrapMixin, CustomFieldFilterForm): choices=IPADDRESS_ROLE_CHOICES, annotate=IPAddress.objects.all(), annotate_field='role', + include_null=True, required=False ) diff --git a/netbox/utilities/forms.py b/netbox/utilities/forms.py index b531fa637..010db31e1 100644 --- a/netbox/utilities/forms.py +++ b/netbox/utilities/forms.py @@ -538,6 +538,8 @@ class AnnotatedMultipleChoiceField(forms.MultipleChoiceField): """ def annotate_choices(self): + + # Aggregate objects by choice field values queryset = self.annotate.values( self.annotate_field ).annotate( @@ -548,18 +550,31 @@ class AnnotatedMultipleChoiceField(forms.MultipleChoiceField): choice_counts = { c[self.annotate_field]: c['count'] for c in queryset } - annotated_choices = [ - (c[0], '{} ({})'.format(c[1], choice_counts.get(c[0], 0))) for c in self.static_choices - ] + + annotated_choices = [] + + # Optionally add a "none" choice + if self.include_null: + annotated_choices.append(( + settings.FILTERS_NULL_CHOICE_VALUE, + '-- {} --'.format(settings.FILTERS_NULL_CHOICE_LABEL) + )) + + # Append each choice and its annotated count + for c in self.static_choices: + annotated_choices.append( + (c[0], '{} ({})'.format(c[1], choice_counts.get(c[0], 0))) + ) return annotated_choices - def __init__(self, choices, annotate, annotate_field, *args, **kwargs): + def __init__(self, choices, annotate, annotate_field, include_null=False, **kwargs): self.annotate = annotate self.annotate_field = annotate_field + self.include_null = include_null self.static_choices = unpack_grouped_choices(choices) - super().__init__(choices=self.annotate_choices, *args, **kwargs) + super().__init__(choices=self.annotate_choices, **kwargs) class LaxURLField(forms.URLField):