Просмотр исходного кода

Fixes #23748: Report foreign component on its selector

The validation error now names the component template and says it must
belong to the same device type, which also reads correctly for a
component on a module type. The edit form reports it on the chosen
component selector, since the device type can't be changed there. The
REST API still reports it on device_type.
Jason Novinger 12 часов назад
Родитель
Сommit
e8ed46a01a

+ 20 - 6
netbox/dcim/forms/model_forms.py

@@ -1781,6 +1781,10 @@ class InventoryItemTemplateForm(ComponentTemplateForm):
             name=_('Component Assignment')
             name=_('Component Assignment')
         )
         )
     )
     )
+    component_fields = (
+        'consoleporttemplate', 'consoleserverporttemplate', 'frontporttemplate', 'interfacetemplate',
+        'poweroutlettemplate', 'powerporttemplate', 'rearporttemplate',
+    )
 
 
     class Meta:
     class Meta:
         model = InventoryItemTemplate
         model = InventoryItemTemplate
@@ -1817,12 +1821,7 @@ class InventoryItemTemplateForm(ComponentTemplateForm):
         super().clean()
         super().clean()
 
 
         # Handle object assignment
         # Handle object assignment
-        selected_objects = [
-            field for field in (
-                'consoleporttemplate', 'consoleserverporttemplate', 'frontporttemplate', 'interfacetemplate',
-                'poweroutlettemplate', 'powerporttemplate', 'rearporttemplate'
-            ) if self.cleaned_data[field]
-        ]
+        selected_objects = [field for field in self.component_fields if self.cleaned_data[field]]
         if len(selected_objects) > 1:
         if len(selected_objects) > 1:
             raise forms.ValidationError(_("An InventoryItem can only be assigned to a single component."))
             raise forms.ValidationError(_("An InventoryItem can only be assigned to a single component."))
         if selected_objects:
         if selected_objects:
@@ -1830,6 +1829,21 @@ class InventoryItemTemplateForm(ComponentTemplateForm):
         else:
         else:
             self.instance.component = None
             self.instance.component = None
 
 
+    def _update_errors(self, errors):
+        """
+        Report a component on another device type against its selector, as the device type can't be changed
+        when editing.
+        """
+        selected = [field for field in self.component_fields if self.cleaned_data.get(field)]
+        if len(selected) == 1 and hasattr(errors, 'error_dict'):
+            remapped = {}
+            for field, error_list in errors.error_dict.items():
+                for error in error_list:
+                    key = selected[0] if error.code == 'component_device_type' else field
+                    remapped.setdefault(key, []).append(error)
+            errors = forms.ValidationError(remapped)
+        super()._update_errors(errors)
+
 
 
 #
 #
 # Device components
 # Device components

+ 6 - 2
netbox/dcim/models/device_component_templates.py

@@ -1095,10 +1095,14 @@ class InventoryItemTemplate(LtreeModel, ComponentTemplateModel):
     def clean(self):
     def clean(self):
         super().clean()
         super().clean()
 
 
-        # A component template on a module type has no device type, so this check also rejects it
         if self.device_type_id and self.component and self.component.device_type_id != self.device_type_id:
         if self.device_type_id and self.component and self.component.device_type_id != self.device_type_id:
             raise ValidationError({
             raise ValidationError({
-                'device_type': _("Cannot assign inventory item template to component template on another device type.")
+                'device_type': ValidationError(
+                    _("Component template ({component}) must belong to the same device type.").format(
+                        component=self.component
+                    ),
+                    code='component_device_type',
+                )
             })
             })
 
 
     def instantiate(self, parent=None, **kwargs):
     def instantiate(self, parent=None, **kwargs):

+ 39 - 1
netbox/dcim/tests/test_forms.py

@@ -3,7 +3,7 @@ from unittest.mock import patch
 import yaml
 import yaml
 from django import forms
 from django import forms
 from django.template.loader import render_to_string
 from django.template.loader import render_to_string
-from django.test import TestCase
+from django.test import TestCase, tag
 
 
 from circuits.models import CircuitTermination
 from circuits.models import CircuitTermination
 from dcim.choices import (
 from dcim.choices import (
@@ -1887,3 +1887,41 @@ class SiteFormTestCase(TestCase):
         self.assertEqual(site.asns.count(), M2MAddRemoveFields.THRESHOLD)
         self.assertEqual(site.asns.count(), M2MAddRemoveFields.THRESHOLD)
         self.assertTrue(site.asns.filter(pk__in=add_pks).count() == 3)
         self.assertTrue(site.asns.filter(pk__in=add_pks).count() == 3)
         self.assertFalse(site.asns.filter(pk__in=remove_pks).exists())
         self.assertFalse(site.asns.filter(pk__in=remove_pks).exists())
+
+
+class InventoryItemTemplateFormTestCase(TestCase):
+
+    @tag('regression')  # Ref: #23748
+    def test_foreign_component_error_on_component_field(self):
+        """
+        The device type can't be changed when editing, so the error must point at the component to change.
+        """
+        manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
+        device_type = DeviceType.objects.create(manufacturer=manufacturer, model='Device Type 1', slug='device-type-1')
+        other_device_type = DeviceType.objects.create(
+            manufacturer=manufacturer, model='Device Type 2', slug='device-type-2'
+        )
+        interface = InterfaceTemplate.objects.create(
+            device_type=other_device_type, name='eth1', type=InterfaceTypeChoices.TYPE_1GE_FIXED
+        )
+        # Saved without validation, as the REST API allowed before #23748
+        saved = InventoryItemTemplate.objects.create(device_type=device_type, name='Optic', component=interface)
+        data = {'device_type': device_type.pk, 'name': 'Optic', 'interfacetemplate': interface.pk}
+
+        for instance in (None, saved):
+            with self.subTest(editing=instance is not None):
+                form = InventoryItemTemplateForm(data=data, instance=instance)
+                self.assertFalse(form.is_valid())
+                self.assertNotIn('device_type', form.errors)
+                self.assertEqual(
+                    form.errors['interfacetemplate'],
+                    ['Component template (eth1) must belong to the same device type.']
+                )
+
+        # With two components selected, the saved component is still validated, so no selector gets its error
+        own_console_port = ConsolePortTemplate.objects.create(device_type=device_type, name='Console')
+        form = InventoryItemTemplateForm(
+            data={**data, 'consoleporttemplate': own_console_port.pk}, instance=saved
+        )
+        self.assertFalse(form.is_valid())
+        self.assertNotIn('consoleporttemplate', form.errors)

+ 17 - 12
netbox/dcim/tests/test_models.py

@@ -4790,25 +4790,30 @@ class InventoryItemTemplateTestCase(TestCase):
         )
         )
         InventoryItemTemplate(device_type=device_type, name='Optic', component=own_interface).full_clean()
         InventoryItemTemplate(device_type=device_type, name='Optic', component=own_interface).full_clean()
 
 
-        foreign_interfaces = (
-            InterfaceTemplate.objects.create(
-                device_type=other_device_type, name='eth0', type=InterfaceTypeChoices.TYPE_1GE_FIXED
-            ),
-            InterfaceTemplate.objects.create(
-                module_type=module_type, name='eth{module}', type=InterfaceTypeChoices.TYPE_1GE_FIXED
-            ),
-        )
-        for interface in foreign_interfaces:
+        other_device_type_interface = InterfaceTemplate.objects.create(
+            device_type=other_device_type, name='eth1', type=InterfaceTypeChoices.TYPE_1GE_FIXED
+        )
+        module_type_interface = InterfaceTemplate.objects.create(
+            module_type=module_type, name='eth{module}', type=InterfaceTypeChoices.TYPE_1GE_FIXED
+        )
+        for interface, message in (
+            (other_device_type_interface, 'Component template (eth1) must belong to the same device type.'),
+            (module_type_interface, 'Component template (eth{module}) must belong to the same device type.'),
+        ):
             with self.subTest(interface=interface):
             with self.subTest(interface=interface):
                 template = InventoryItemTemplate(device_type=device_type, name='Optic', component=interface)
                 template = InventoryItemTemplate(device_type=device_type, name='Optic', component=interface)
                 with self.assertRaises(ValidationError) as cm:
                 with self.assertRaises(ValidationError) as cm:
                     template.full_clean()
                     template.full_clean()
-                self.assertIn('device_type', cm.exception.message_dict)
+                self.assertEqual(cm.exception.message_dict['device_type'], [message])
 
 
-        template = InventoryItemTemplate(name='Optic', component=foreign_interfaces[0])
+        # Without a device type, report only the missing field, not a mismatch
+        template = InventoryItemTemplate(name='Optic', component=other_device_type_interface)
         with self.assertRaises(ValidationError) as cm:
         with self.assertRaises(ValidationError) as cm:
             template.full_clean()
             template.full_clean()
-        self.assertEqual(len(cm.exception.message_dict['device_type']), 1)
+        self.assertNotIn(
+            'Component template (eth1) must belong to the same device type.',
+            cm.exception.message_dict['device_type']
+        )
 
 
 
 
 class InventoryItemTemplateCycleTestCase(TestCase):
 class InventoryItemTemplateCycleTestCase(TestCase):