From f62b2c7552c5af8d696b898111fab6127d6205ef Mon Sep 17 00:00:00 2001 From: Renato Almeida de Oliveira Zaroubin Date: Tue, 11 Mar 2025 22:46:19 +0000 Subject: [PATCH] Refactor InventoryItemImportForm clean method --- netbox/dcim/forms/bulk_import.py | 44 +++++++++++++++++++------------- 1 file changed, 26 insertions(+), 18 deletions(-) diff --git a/netbox/dcim/forms/bulk_import.py b/netbox/dcim/forms/bulk_import.py index 92f7220da..d61350987 100644 --- a/netbox/dcim/forms/bulk_import.py +++ b/netbox/dcim/forms/bulk_import.py @@ -1161,27 +1161,35 @@ class InventoryItemImportForm(NetBoxModelImportForm): else: self.fields['parent'].queryset = InventoryItem.objects.none() - def clean_component_name(self): - content_type = self.cleaned_data.get('component_type') - component_name = self.cleaned_data.get('component_name') + def clean(self): + cleaned_data = self.cleaned_data + content_type = cleaned_data.get('component_type') + component_name = cleaned_data.get('component_name') device = self.cleaned_data.get("device") - if not device and hasattr(self, 'instance') and hasattr(self.instance, 'device'): - device = self.instance.device - - if not all([device, content_type, component_name]): - return None - - model = content_type.model_class() - try: - component = model.objects.get(device=device, name=component_name) - self.instance.component = component - except ObjectDoesNotExist: - raise forms.ValidationError( - _("Component not found: {device} - {component_name}").format( - device=device, component_name=component_name + if content_type: + if device is None: + cleaned_data.pop('component_type') + if component_name is None: + cleaned_data.pop('component_type') + raise forms.ValidationError( + _("Component name must be specified when component type is specified") ) - ) + if all([device, component_name]): + try: + model = content_type.model_class() + component = model.objects.get(device=device, name=component_name) + self.instance.component = component + except ObjectDoesNotExist: + cleaned_data.pop('component_type') + cleaned_data.pop('component_name') + raise forms.ValidationError( + _("Component not found: {device} - {component_name}").format( + device=device, component_name=component_name + ) + ) + + return cleaned_data #