Fixes #2779: Include "none" option when filter IP addresses by role

This commit is contained in:
Jeremy Stretch 2019-01-15 11:26:41 -05:00
parent 4a290f3834
commit 1d7a7e2d1d
3 changed files with 22 additions and 5 deletions

View File

@ -2,6 +2,7 @@ v2.5.4 (FUTURE)
## Bug Fixes ## 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) * [#2783](https://github.com/digitalocean/netbox/issues/2783) - Fix AttributeError exception when attempting to delete region(s)
--- ---

View File

@ -913,6 +913,7 @@ class IPAddressFilterForm(BootstrapMixin, CustomFieldFilterForm):
choices=IPADDRESS_ROLE_CHOICES, choices=IPADDRESS_ROLE_CHOICES,
annotate=IPAddress.objects.all(), annotate=IPAddress.objects.all(),
annotate_field='role', annotate_field='role',
include_null=True,
required=False required=False
) )

View File

@ -538,6 +538,8 @@ class AnnotatedMultipleChoiceField(forms.MultipleChoiceField):
""" """
def annotate_choices(self): def annotate_choices(self):
# Aggregate objects by choice field values
queryset = self.annotate.values( queryset = self.annotate.values(
self.annotate_field self.annotate_field
).annotate( ).annotate(
@ -548,18 +550,31 @@ class AnnotatedMultipleChoiceField(forms.MultipleChoiceField):
choice_counts = { choice_counts = {
c[self.annotate_field]: c['count'] for c in queryset 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 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 = annotate
self.annotate_field = annotate_field self.annotate_field = annotate_field
self.include_null = include_null
self.static_choices = unpack_grouped_choices(choices) 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): class LaxURLField(forms.URLField):