From f649b9f04fe225599890012f22fde68176ed9b7c Mon Sep 17 00:00:00 2001 From: Jeremy Stretch Date: Tue, 31 Dec 2019 12:41:02 -0500 Subject: [PATCH] Fixes #3106: Restrict queryset of chained fields when form validation fails --- docs/release-notes/version-2.6.md | 1 + netbox/utilities/forms.py | 8 +++++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/release-notes/version-2.6.md b/docs/release-notes/version-2.6.md index fce50fbe4..548492438 100644 --- a/docs/release-notes/version-2.6.md +++ b/docs/release-notes/version-2.6.md @@ -8,6 +8,7 @@ ## Bug Fixes +* [#3106](https://github.com/netbox-community/netbox/issues/3106) - Restrict queryset of chained fields when form validation fails * [#3695](https://github.com/netbox-community/netbox/issues/3695) - Include A/Z termination sites for circuits in global search * [#3712](https://github.com/netbox-community/netbox/issues/3712) - Scrolling to target (hash) did not account for the header size * [#3780](https://github.com/netbox-community/netbox/issues/3780) - Fix AttributeError exception in API docs diff --git a/netbox/utilities/forms.py b/netbox/utilities/forms.py index 5f920930d..44d76186d 100644 --- a/netbox/utilities/forms.py +++ b/netbox/utilities/forms.py @@ -701,16 +701,22 @@ class ChainedFieldsMixin(forms.BaseForm): else: break + # Limit field queryset by chained field values if filters_dict: field.queryset = field.queryset.filter(**filters_dict) + # Editing an existing instance; limit field to its current value elif not self.is_bound and getattr(self, 'instance', None) and hasattr(self.instance, field_name): obj = getattr(self.instance, field_name) if obj is not None: field.queryset = field.queryset.filter(pk=obj.pk) else: field.queryset = field.queryset.none() - elif not self.is_bound: + # Creating a new instance with no bound data; nullify queryset + elif not self.data.get(field_name): field.queryset = field.queryset.none() + # Creating a new instance with bound data; limit queryset to the specified value + else: + field.queryset = field.queryset.filter(pk=self.data.get(field_name)) class ReturnURLForm(forms.Form):