Clean up boilerplate form field initialization code #941

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

Originally created by @jeremystretch on GitHub (May 11, 2017).

Many of the forms within NetBox utilize chained select fields which are populated with options dynamically as the user make selections. Additional logic is necessary to populate these fields when the form is first rendered and bound or initial data is provided. Currently, this is accomplished using boilerplate which follows a pattern similar to the code below:

        # Initialize device choices if rack or site is set
        if self.initial.get('rack'):
            self.fields['device'].queryset = Device.objects.filter(rack=self.initial['rack'])
        elif self.initial.get('site'):
            self.fields['device'].queryset = Device.objects.filter(site=self.initial['site'], rack__isnull=True)
        else:
            self.fields['device'].choices = []

This can be simplified by introducing a new type of form field which will automatically perform the necessary queryset filtering on form initialization.

Originally created by @jeremystretch on GitHub (May 11, 2017). Many of the forms within NetBox utilize chained select fields which are populated with options dynamically as the user make selections. Additional logic is necessary to populate these fields when the form is first rendered and bound or initial data is provided. Currently, this is accomplished using boilerplate which follows a pattern similar to the code below: ``` # Initialize device choices if rack or site is set if self.initial.get('rack'): self.fields['device'].queryset = Device.objects.filter(rack=self.initial['rack']) elif self.initial.get('site'): self.fields['device'].queryset = Device.objects.filter(site=self.initial['site'], rack__isnull=True) else: self.fields['device'].choices = [] ``` This can be simplified by introducing a new type of form field which will automatically perform the necessary queryset filtering on form initialization.
adam added the type: feature label 2025-12-29 16:27:08 +01:00
adam closed this issue 2025-12-29 16:27:08 +01:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/netbox#941