Create custom form field for choice-based filters #1535

Closed
opened 2025-12-29 16:32:46 +01:00 by adam · 0 comments
Owner

Originally created by @jeremystretch on GitHub (Feb 6, 2018).

Issue type

[x] Feature request
[ ] Bug report
[ ] Documentation

Environment

  • Python version: 3.5.2
  • NetBox version: 2.2.9

Description

NetBox currently employs custom functions to generate the options for choice-based fields in filter forms. For example, the following is for site status selection:

def site_status_choices():
    status_counts = {}
    for status in Site.objects.values('status').annotate(count=Count('status')).order_by('status'):
        status_counts[status['status']] = status['count']
    return [(s[0], '{} ({})'.format(s[1], status_counts.get(s[0], 0))) for s in SITE_STATUS_CHOICES]

class SiteFilterForm(BootstrapMixin, CustomFieldFilterForm):
    model = Site
    status = forms.MultipleChoiceField(choices=site_status_choices, required=False)
    ...

The logic used to calculate and attach the count of each option is replicated in the same manner for several fields. We should be able to devise a simple custom form field that can be re-used without duplicating this boilerplate code.

Originally created by @jeremystretch on GitHub (Feb 6, 2018). ### Issue type [x] Feature request <!-- An enhancement of existing functionality --> [ ] Bug report <!-- Unexpected or erroneous behavior --> [ ] Documentation <!-- A modification to the documentation --> ### Environment * Python version: 3.5.2 * NetBox version: 2.2.9 ### Description NetBox currently employs custom functions to generate the options for choice-based fields in filter forms. For example, the following is for site status selection: ```python def site_status_choices(): status_counts = {} for status in Site.objects.values('status').annotate(count=Count('status')).order_by('status'): status_counts[status['status']] = status['count'] return [(s[0], '{} ({})'.format(s[1], status_counts.get(s[0], 0))) for s in SITE_STATUS_CHOICES] class SiteFilterForm(BootstrapMixin, CustomFieldFilterForm): model = Site status = forms.MultipleChoiceField(choices=site_status_choices, required=False) ... ``` The logic used to calculate and attach the count of each option is replicated in the same manner for several fields. We should be able to devise a simple custom form field that can be re-used without duplicating this boilerplate code.
adam added the status: acceptedtype: housekeeping labels 2025-12-29 16:32:46 +01:00
adam closed this issue 2025-12-29 16:32:46 +01:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/netbox#1535