Sfoglia il codice sorgente

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

Jeremy Stretch 7 anni fa
parent
commit
1d7a7e2d1d
3 ha cambiato i file con 22 aggiunte e 5 eliminazioni
  1. 1 0
      CHANGELOG.md
  2. 1 0
      netbox/ipam/forms.py
  3. 20 5
      netbox/utilities/forms.py

+ 1 - 0
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)
 
 ---

+ 1 - 0
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
     )
 

+ 20 - 5
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):