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

Closes #22260: Add front and rear images to module types (#23720)

Module types gain optional front and rear images, editable in the UI
and REST API and shown on the module type and module pages. Image files
are deleted only after the change commits and only once no module type
references them, and the media view serves them only to users who can
view the module type.
Martin Hauser 11 часов назад
Родитель
Сommit
9eabaf6871

+ 4 - 0
docs/models/dcim/moduletype.md

@@ -83,6 +83,10 @@ The cooling method employed by modules of this type (air, liquid, hybrid, or imm
 
 The date after which this module type is no longer supported by its manufacturer. This can be used to identify modules approaching or past their support horizon to aid in hardware lifecycle planning.
 
+### Front & Rear Images
+
+Users can upload images of the module's front and rear panels. These are displayed on the module type and its module instances.
+
 ### Profile
 
 The assigned [profile](./moduletypeprofile.md) for the type of module. Profiles can be used to classify module types by function (e.g. power supply, hard disk, etc.), and they support the addition of user-configurable attributes on module types. The assignment of a module type to a profile is optional.

+ 4 - 2
netbox/dcim/api/serializers_/devicetypes.py

@@ -124,6 +124,8 @@ class ModuleTypeSerializer(PrimaryModelSerializer):
         allow_null=True
     )
     cooling_method = ChoiceField(choices=CoolingMethodChoices, allow_blank=True, required=False, allow_null=True)
+    front_image = serializers.ImageField(required=False, allow_null=True)
+    rear_image = serializers.ImageField(required=False, allow_null=True)
     attributes = AttributesField(
         source='attribute_data',
         required=False,
@@ -147,8 +149,8 @@ class ModuleTypeSerializer(PrimaryModelSerializer):
         model = ModuleType
         fields = [
             'id', 'url', 'display_url', 'display', 'profile', 'manufacturer', 'model', 'part_number', 'airflow',
-            'cooling_method', 'weight', 'weight_unit', 'end_of_life', 'description', 'attributes', 'module_bay_types',
-            'owner', 'comments', 'tags', 'custom_fields',
+            'cooling_method', 'weight', 'weight_unit', 'end_of_life', 'front_image', 'rear_image', 'description',
+            'attributes', 'module_bay_types', 'owner', 'comments', 'tags', 'custom_fields',
             'created', 'last_updated', 'module_count', 'console_port_template_count',
             'console_server_port_template_count', 'power_port_template_count', 'power_outlet_template_count',
             'cooling_intake_template_count', 'cooling_outflow_template_count', 'interface_template_count',

+ 18 - 0
netbox/dcim/filtersets.py

@@ -919,6 +919,14 @@ class ModuleTypeFilterSet(AttributeFiltersMixin, PrimaryModelFilterSet):
         to_field_name='slug',
         label=_('Module bay type (slug)'),
     )
+    has_front_image = django_filters.BooleanFilter(
+        label=_('Has a front image'),
+        method='_has_front_image'
+    )
+    has_rear_image = django_filters.BooleanFilter(
+        label=_('Has a rear image'),
+        method='_has_rear_image'
+    )
     console_ports = django_filters.BooleanFilter(
         method='_console_ports',
         label=_('Has console ports'),
@@ -979,6 +987,16 @@ class ModuleTypeFilterSet(AttributeFiltersMixin, PrimaryModelFilterSet):
             Q(comments__icontains=value)
         )
 
+    def _has_front_image(self, queryset, name, value):
+        if value:
+            return queryset.exclude(front_image='')
+        return queryset.filter(front_image='')
+
+    def _has_rear_image(self, queryset, name, value):
+        if value:
+            return queryset.exclude(rear_image='')
+        return queryset.filter(rear_image='')
+
     def _console_ports(self, queryset, name, value):
         return queryset.exclude(consoleporttemplates__isnull=value)
 

+ 15 - 0
netbox/dcim/forms/filtersets.py

@@ -772,6 +772,7 @@ class ModuleTypeFilterForm(PrimaryModelFilterSetForm):
             'module_bay_type_id', name=_('Hardware')
         ),
         FieldSet('cooling_method', 'airflow', name=_('Cooling')),
+        FieldSet('has_front_image', 'has_rear_image', name=_('Images')),
         FieldSet(
             'console_ports', 'console_server_ports', 'power_ports', 'power_outlets', 'interfaces',
             'pass_through_ports', 'module_bays', name=_('Components')
@@ -807,6 +808,20 @@ class ModuleTypeFilterForm(PrimaryModelFilterSetForm):
         required=False,
         min_value=0,
     )
+    has_front_image = forms.NullBooleanField(
+        required=False,
+        label=_('Has a front image'),
+        widget=forms.Select(
+            choices=BOOLEAN_WITH_BLANK_CHOICES
+        )
+    )
+    has_rear_image = forms.NullBooleanField(
+        required=False,
+        label=_('Has a rear image'),
+        widget=forms.Select(
+            choices=BOOLEAN_WITH_BLANK_CHOICES
+        )
+    )
     console_ports = forms.NullBooleanField(
         required=False,
         label=_('Has console ports'),

+ 8 - 1
netbox/dcim/forms/model_forms.py

@@ -642,6 +642,7 @@ class ModuleTypeForm(PrimaryModelForm):
             FieldSet('cooling_method', 'airflow', name=_('Cooling')),
             FieldSet('module_bay_types', name=_('Bay Type Compatibility')),
             FieldSet('end_of_life', name=_('Lifecycle')),
+            FieldSet('front_image', 'rear_image', name=_('Images')),
             FieldSet('profile', *self.attr_fields, name=_('Profile & Attributes'), html_id='profile-attributes')
         ]
 
@@ -649,9 +650,15 @@ class ModuleTypeForm(PrimaryModelForm):
         model = ModuleType
         fields = [
             'profile', 'manufacturer', 'model', 'part_number', 'description', 'cooling_method', 'airflow', 'weight',
-            'weight_unit', 'module_bay_types', 'end_of_life', 'owner', 'comments', 'tags',
+            'weight_unit', 'module_bay_types', 'end_of_life', 'front_image', 'rear_image', 'owner', 'comments', 'tags',
         ]
         widgets = {
+            'front_image': ClearableFileInput(attrs={
+                'accept': DEVICETYPE_IMAGE_FORMATS
+            }),
+            'rear_image': ClearableFileInput(attrs={
+                'accept': DEVICETYPE_IMAGE_FORMATS
+            }),
             'end_of_life': DatePicker(),
         }
 

+ 2 - 0
netbox/dcim/graphql/filters.py

@@ -859,6 +859,8 @@ class ModuleTypeFilter(ImageAttachmentFilterMixin, WeightFilterMixin, PrimaryMod
         strawberry_django.filter_field()
     )
     end_of_life: DateFilterLookup | None = strawberry_django.filter_field()
+    front_image: StrFilterLookup | None = strawberry_django.filter_field()
+    rear_image: StrFilterLookup | None = strawberry_django.filter_field()
     consoleporttemplates: Annotated['ConsolePortTemplateFilter', strawberry.lazy('dcim.graphql.filters')] | None = (
         strawberry_django.filter_field(name='console_port_templates')
     )

+ 2 - 0
netbox/dcim/graphql/types.py

@@ -809,6 +809,8 @@ class ModuleTypeType(PrimaryObjectType):
     front_port_template_count: BigInt
     rear_port_template_count: BigInt
     module_bay_template_count: BigInt
+    front_image: strawberry_django.fields.types.DjangoImageType | None
+    rear_image: strawberry_django.fields.types.DjangoImageType | None
     profile: Annotated["ModuleTypeProfileType", strawberry.lazy('dcim.graphql.types')] | None
     manufacturer: Annotated["ManufacturerType", strawberry.lazy('dcim.graphql.types')]
     module_bay_types: list[Annotated["ModuleBayTypeType", strawberry.lazy('dcim.graphql.types')]]

+ 21 - 0
netbox/dcim/migrations/0254_moduletype_images.py

@@ -0,0 +1,21 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('dcim', '0253_macblock'),
+    ]
+
+    operations = [
+        migrations.AddField(
+            model_name='moduletype',
+            name='front_image',
+            field=models.ImageField(blank=True, upload_to='moduletype-images'),
+        ),
+        migrations.AddField(
+            model_name='moduletype',
+            name='rear_image',
+            field=models.ImageField(blank=True, upload_to='moduletype-images'),
+        ),
+    ]

+ 44 - 0
netbox/dcim/models/modules.py

@@ -1,4 +1,5 @@
 from collections.abc import Iterable, Mapping
+from functools import partial
 
 import jsonschema
 import yaml
@@ -165,6 +166,14 @@ class ModuleType(ImageAttachmentsMixin, PrimaryModel, WeightMixin):
         null=True,
         help_text=_('The date after which this module type is no longer supported by the manufacturer')
     )
+    front_image = models.ImageField(
+        upload_to='moduletype-images',
+        blank=True
+    )
+    rear_image = models.ImageField(
+        upload_to='moduletype-images',
+        blank=True
+    )
     attribute_data = models.JSONField(
         blank=True,
         null=True,
@@ -319,6 +328,41 @@ class ModuleType(ImageAttachmentsMixin, PrimaryModel, WeightMixin):
         else:
             self.attribute_data = None
 
+    def save(self, *args, **kwargs):
+        update_fields = normalize_update_fields(kwargs)
+        using = kwargs.get('using') or router.db_for_write(self.__class__, instance=self)
+        deferred_fields = self.get_deferred_fields()
+        image_fields = [
+            name for name in ('front_image', 'rear_image')
+            if name not in deferred_fields and (update_fields is None or name in update_fields)
+        ]
+
+        # Read persisted filenames only for image fields included in this save.
+        original_images = {}
+        if self.pk is not None and image_fields:
+            original_images = (
+                ModuleType.objects.using(using).filter(pk=self.pk).order_by().values(*image_fields).first() or {}
+            )
+
+        kwargs['using'] = using
+        ret = super().save(*args, **kwargs)
+
+        for field_name, name in original_images.items():
+            if name and getattr(self, field_name).name != name:
+                transaction.on_commit(
+                    partial(self._delete_image_file, field_name, name, using), using=using, robust=True
+                )
+
+        return ret
+
+    @classmethod
+    def _delete_image_file(cls, field_name, name, using):
+        """
+        Delete an image file only when no module type still references it.
+        """
+        if not cls.objects.using(using).filter(models.Q(front_image=name) | models.Q(rear_image=name)).exists():
+            cls._meta.get_field(field_name).storage.delete(name)
+
     def get_cooling_method_color(self):
         return CoolingMethodChoices.colors.get(self.cooling_method)
 

+ 20 - 1
netbox/dcim/signals.py

@@ -1,8 +1,9 @@
 import logging
+from functools import partial
 
 from django.db import transaction
 from django.db.models import Q
-from django.db.models.signals import post_delete, post_save, pre_save
+from django.db.models.signals import post_delete, post_save, pre_delete, pre_save
 from django.dispatch import receiver
 
 from dcim.choices import CableEndChoices, LinkStatusChoices
@@ -17,6 +18,7 @@ from .models import (
     Device,
     Interface,
     Location,
+    ModuleType,
     PathEndpoint,
     PortMapping,
     PowerPanel,
@@ -503,3 +505,20 @@ def update_mac_address_interface(instance, created, raw, **kwargs):
     if created and not raw and instance.primary_mac_address:
         instance.primary_mac_address.assigned_object = instance
         instance.primary_mac_address.save()
+
+
+#
+# Module types
+#
+
+@receiver(pre_delete, sender=ModuleType)
+def delete_module_type_images(sender, instance, using, **kwargs):
+    """
+    Remove stored module type images after the deletion commits.
+    """
+    images = (
+        sender.objects.using(using).filter(pk=instance.pk).order_by().values('front_image', 'rear_image').first() or {}
+    )
+    for field_name, name in images.items():
+        if name:
+            transaction.on_commit(partial(sender._delete_image_file, field_name, name, using), using=using, robust=True)

+ 101 - 2
netbox/dcim/tests/test_api.py

@@ -1829,6 +1829,23 @@ class ModuleTypeTestCase(APIViewTestCases.APIViewTestCase):
         'airflow': 'not-a-valid-airflow',
     }
     user_permissions = ('dcim.view_manufacturer', )
+    graphql_filter_tests = (
+        GraphQLFilterTest(
+            name='front_image__exact',
+            filters='front_image: {exact: "moduletype-images/front2.png"}',
+            expected=lambda qs: qs.filter(model='Module Type 2'),
+        ),
+        GraphQLFilterTest(
+            name='rear_image__exact',
+            filters='rear_image: {exact: "moduletype-images/rear3.png"}',
+            expected=lambda qs: qs.filter(model='Module Type 3'),
+        ),
+        GraphQLFilterTest(
+            name='front_image__exact_empty',
+            filters='front_image: {exact: ""}',
+            expected=lambda qs: qs.filter(model__in=['Module Type 1', 'Module Type 3']),
+        ),
+    )
 
     @classmethod
     def setUpTestData(cls):
@@ -1841,8 +1858,16 @@ class ModuleTypeTestCase(APIViewTestCases.APIViewTestCase):
 
         module_types = (
             ModuleType(manufacturer=manufacturers[0], model='Module Type 1'),
-            ModuleType(manufacturer=manufacturers[0], model='Module Type 2'),
-            ModuleType(manufacturer=manufacturers[0], model='Module Type 3'),
+            ModuleType(
+                manufacturer=manufacturers[0],
+                model='Module Type 2',
+                front_image='moduletype-images/front2.png',
+            ),
+            ModuleType(
+                manufacturer=manufacturers[0],
+                model='Module Type 3',
+                rear_image='moduletype-images/rear3.png',
+            ),
         )
         ModuleType.objects.bulk_create(module_types)
 
@@ -1872,6 +1897,80 @@ class ModuleTypeTestCase(APIViewTestCases.APIViewTestCase):
             },
         ]
 
+    def test_create_object_with_images(self):
+        """
+        Create a ModuleType with front/rear images via a multipart request.
+        """
+        self.add_permissions('dcim.add_moduletype')
+        # A nested field is read from "<field>.id" in a multipart request
+        data = {
+            'manufacturer.id': Manufacturer.objects.first().pk,
+            'model': 'Module Type 7',
+            'front_image': create_test_image('front.png'),
+            'rear_image': create_test_image('rear.png'),
+        }
+
+        with tempfile.TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
+            response = self.client.post(self._get_list_url(), data, format='multipart', **self.header)
+            self.assertHttpStatus(response, status.HTTP_201_CREATED)
+            module_type = ModuleType.objects.get(pk=response.data['id'])
+            for image in (module_type.front_image, module_type.rear_image):
+                self.assertTrue(os.path.exists(image.path))
+                self.assertTrue(image.name.startswith('moduletype-images/'))
+
+    def test_update_object_image(self):
+        """
+        Replace a ModuleType's front image via a multipart request, which should delete the original file.
+        """
+        self.add_permissions('dcim.change_moduletype')
+
+        with tempfile.TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
+            module_type = ModuleType.objects.first()
+            module_type.front_image = create_test_image('front.png')
+            module_type.rear_image = create_test_image('rear.png')
+            module_type.save()
+            front_image_path = module_type.front_image.path
+            rear_image_path = module_type.rear_image.path
+
+            data = {
+                'front_image': create_test_image('front2.png'),
+            }
+            with self.captureOnCommitCallbacks(execute=True):
+                response = self.client.patch(
+                    self._get_detail_url(module_type), data, format='multipart', **self.header
+                )
+            self.assertHttpStatus(response, status.HTTP_200_OK)
+            module_type.refresh_from_db()
+            self.assertFalse(os.path.exists(front_image_path))
+            self.assertTrue(os.path.exists(module_type.front_image.path))
+            self.assertNotEqual(module_type.front_image.path, front_image_path)
+            self.assertTrue(os.path.exists(rear_image_path))
+
+    def test_clear_object_image(self):
+        """
+        Clear a ModuleType's rear image via a JSON request, which should delete its file.
+        """
+        self.add_permissions('dcim.change_moduletype')
+
+        with tempfile.TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
+            module_type = ModuleType.objects.first()
+            module_type.front_image = create_test_image('front.png')
+            module_type.rear_image = create_test_image('rear.png')
+            module_type.save()
+            front_image_path = module_type.front_image.path
+            rear_image_path = module_type.rear_image.path
+
+            with self.captureOnCommitCallbacks(execute=True):
+                response = self.client.patch(
+                    self._get_detail_url(module_type), {'rear_image': None}, format='json', **self.header
+                )
+            self.assertHttpStatus(response, status.HTTP_200_OK)
+            self.assertIsNone(response.data['rear_image'])
+            module_type.refresh_from_db()
+            self.assertFalse(module_type.rear_image)
+            self.assertFalse(os.path.exists(rear_image_path))
+            self.assertTrue(os.path.exists(front_image_path))
+
 
 class ModuleTypeProfileTestCase(APIViewTestCases.APIViewTestCase):
     model = ModuleTypeProfile

+ 22 - 1
netbox/dcim/tests/test_filtersets.py

@@ -1697,7 +1697,7 @@ class DeviceTypeTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
 class ModuleTypeTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
     queryset = ModuleType.objects.all()
     filterset = ModuleTypeFilterSet
-    ignore_fields = ['attribute_data']
+    ignore_fields = ['attribute_data', 'front_image', 'rear_image']
 
     PROFILE_SCHEMA = {
         "properties": {
@@ -1744,6 +1744,8 @@ class ModuleTypeTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
                 airflow=ModuleAirflowChoices.FRONT_TO_REAR,
                 cooling_method=CoolingMethodChoices.METHOD_LIQUID,
                 end_of_life='2030-01-01',
+                front_image='moduletype-images/front1.png',
+                rear_image='moduletype-images/rear1.png',
                 profile=module_type_profiles[0],
                 attribute_data={
                     'string': 'string1',
@@ -1762,6 +1764,7 @@ class ModuleTypeTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
                 airflow=ModuleAirflowChoices.REAR_TO_FRONT,
                 cooling_method=CoolingMethodChoices.METHOD_HYBRID,
                 end_of_life='2035-06-30',
+                front_image='moduletype-images/front2.png',
                 profile=module_type_profiles[1],
                 attribute_data={
                     'string': 'string2',
@@ -1901,6 +1904,24 @@ class ModuleTypeTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         params = {'module_bays': 'false'}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
 
+    def test_has_front_image(self):
+        """
+        Filter by the presence of a front image.
+        """
+        params = {'has_front_image': True}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+        params = {'has_front_image': False}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+
+    def test_has_rear_image(self):
+        """
+        Filter by the presence of a rear image.
+        """
+        params = {'has_rear_image': True}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
+        params = {'has_rear_image': False}
+        self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)
+
     def test_weight(self):
         params = {'weight': [10, 20]}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)

+ 49 - 2
netbox/dcim/tests/test_forms.py

@@ -1,8 +1,9 @@
+import tempfile
 from unittest.mock import patch
 
 from django import forms
 from django.template.loader import render_to_string
-from django.test import TestCase
+from django.test import TestCase, override_settings
 
 from circuits.models import CircuitTermination
 from dcim.choices import (
@@ -23,7 +24,7 @@ from dcim.tests.test_module_moves import fail_after
 from ipam.models import ASN, RIR, VLAN
 from utilities.exceptions import AbortRequest
 from utilities.forms.rendering import M2MAddRemoveFields
-from utilities.testing import create_test_device
+from utilities.testing import create_test_device, create_test_image
 from virtualization.models import Cluster, ClusterGroup, ClusterType
 
 
@@ -280,6 +281,52 @@ class ModuleTypeFormTestCase(TestCase):
             },
         )
 
+    def test_upload_and_clear_images(self):
+        """
+        Upload images through the form, then clear the front image, which should delete only its file.
+        """
+        data = {
+            'manufacturer': self.manufacturer.pk,
+            'model': 'Module Type 1',
+            'profile': self.profile.pk,
+            'attr_media': ['copper', 'qsfp28'],
+        }
+        form = ModuleTypeForm(data=data, files={
+            'front_image': create_test_image('front.png'),
+            'rear_image': create_test_image('rear.png'),
+        })
+        # A profile change re-renders only the profile-attributes fieldset, which must not hold a picked file
+        profile_fieldset = next(fieldset for fieldset in form.fieldsets if fieldset.html_id == 'profile-attributes')
+        self.assertNotIn('front_image', profile_fieldset.items)
+        self.assertNotIn('rear_image', profile_fieldset.items)
+        self.assertTrue(form.is_multipart())
+
+        with (
+            tempfile.TemporaryDirectory() as media_root,
+            override_settings(MEDIA_ROOT=media_root),
+            patch('utilities.forms.fields.dynamic.get_action_url', return_value='/'),
+        ):
+            self.assertTrue(form.is_valid(), form.errors)
+            module_type = form.save()
+            front_image_name = module_type.front_image.name
+            rear_image_name = module_type.rear_image.name
+            storage = module_type.front_image.storage
+            self.assertTrue(storage.exists(front_image_name))
+            self.assertTrue(storage.exists(rear_image_name))
+            self.assertEqual(module_type.attribute_data, {'media': ['copper', 'qsfp28']})
+
+            form = ModuleTypeForm(data={**data, 'front_image-clear': True}, instance=module_type)
+            self.assertTrue(form.is_valid(), form.errors)
+            with self.captureOnCommitCallbacks(execute=True):
+                form.save()
+
+            module_type.refresh_from_db()
+            self.assertFalse(module_type.front_image)
+            self.assertEqual(module_type.rear_image.name, rear_image_name)
+            self.assertFalse(storage.exists(front_image_name))
+            self.assertTrue(storage.exists(rear_image_name))
+            self.assertEqual(module_type.attribute_data, {'media': ['copper', 'qsfp28']})
+
     def test_enum_array_attribute_uses_multiselect_field(self):
         form = ModuleTypeForm(data={
             'manufacturer': self.manufacturer.pk,

+ 139 - 0
netbox/dcim/tests/test_models.py

@@ -4,6 +4,7 @@ import uuid
 from decimal import Decimal
 from unittest.mock import patch
 
+from django.conf import settings
 from django.core.exceptions import ValidationError
 from django.db import IntegrityError, connection, transaction
 from django.db.models import ProtectedError
@@ -697,6 +698,144 @@ class ModuleTypeTestCase(TestCase):
         )
 
 
+class ModuleTypeImageTestCase(TestCase):
+    """
+    Test the handling of ModuleType front/rear image files.
+    """
+    def setUp(self):
+        media_root = self.enterContext(tempfile.TemporaryDirectory())
+        self.enterContext(override_settings(MEDIA_ROOT=media_root))
+        self.manufacturer = Manufacturer.objects.create(name='Manufacturer 1', slug='manufacturer-1')
+
+    def _create_module_type(self, model='Module Type 1'):
+        """
+        Create a ModuleType with an uploaded front and rear image.
+        """
+        return ModuleType.objects.create(
+            manufacturer=self.manufacturer,
+            model=model,
+            front_image=create_test_image('front.png'),
+            rear_image=create_test_image('rear.png'),
+        )
+
+    def test_saves_without_image_fields_preserve_files(self):
+        """
+        A save which leaves out or defers the image fields should keep the stored files.
+        """
+        module_type = self._create_module_type()
+        front_image_name = module_type.front_image.name
+        storage = module_type.front_image.storage
+        module_type.front_image = create_test_image('replacement.png')
+        module_type.description = 'Updated description'
+
+        with self.captureOnCommitCallbacks(execute=True):
+            module_type.save(update_fields=iter(['description']))
+
+        self.assertTrue(storage.exists(front_image_name))
+        module_type = ModuleType.objects.defer('front_image', 'rear_image').get(pk=module_type.pk)
+        module_type.description = 'Another description'
+        with self.captureOnCommitCallbacks(execute=True):
+            module_type.save()
+
+        self.assertTrue({'front_image', 'rear_image'}.issubset(module_type.get_deferred_fields()))
+        module_type.refresh_from_db()
+        self.assertEqual(module_type.front_image.name, front_image_name)
+        self.assertTrue(storage.exists(front_image_name))
+
+    def test_image_restored_before_commit(self):
+        """
+        Restoring the original image before the transaction commits should keep it and delete the replacement.
+        """
+        module_type = self._create_module_type()
+        original_name = module_type.front_image.name
+        storage = module_type.front_image.storage
+
+        with self.captureOnCommitCallbacks(execute=True):
+            module_type.front_image = create_test_image('replacement.png')
+            module_type.save()
+            replacement_name = module_type.front_image.name
+            module_type.front_image = original_name
+            module_type.save()
+
+        self.assertTrue(storage.exists(original_name))
+        self.assertFalse(storage.exists(replacement_name))
+
+    @override_settings(STORAGES={
+        **settings.STORAGES,
+        'default': {'BACKEND': 'django.core.files.storage.FileSystemStorage', 'OPTIONS': {'allow_overwrite': True}},
+    })
+    def test_image_shared_between_module_types(self):
+        """
+        An image file stored for two module types should be deleted only once neither references it.
+        """
+        # Overwriting storage (S3 by default) gives two uploads of the same file one stored name
+        module_type = self._create_module_type()
+        other_type = self._create_module_type(model='Module Type 2')
+        front_image_name = module_type.front_image.name
+        rear_image_name = module_type.rear_image.name
+        storage = module_type.front_image.storage
+        self.assertEqual(other_type.front_image.name, front_image_name)
+        self.assertEqual(other_type.rear_image.name, rear_image_name)
+
+        with self.captureOnCommitCallbacks(execute=True):
+            module_type.front_image = ''
+            module_type.save()
+        self.assertTrue(storage.exists(front_image_name))
+
+        with self.captureOnCommitCallbacks(execute=True):
+            other_type.delete()
+        self.assertFalse(storage.exists(front_image_name))
+        self.assertTrue(storage.exists(rear_image_name))
+
+    def test_image_deletion_after_commit(self):
+        """
+        Deleting a module type should delete its stored image files once the deletion commits.
+        """
+        for operation in ('instance', 'deferred', 'unsaved_image', 'queryset'):
+            with self.subTest(operation=operation):
+                module_type = self._create_module_type()
+                images = (module_type.front_image.name, module_type.rear_image.name)
+                storage = module_type.front_image.storage
+                if operation == 'deferred':
+                    module_type = ModuleType.objects.only('pk').get(pk=module_type.pk)
+                elif operation == 'unsaved_image':
+                    module_type.front_image = create_test_image('unsaved.png')
+
+                with self.captureOnCommitCallbacks(execute=True):
+                    if operation == 'queryset':
+                        ModuleType.objects.filter(pk=module_type.pk).delete()
+                    else:
+                        module_type.delete()
+                    for name in images:
+                        self.assertTrue(storage.exists(name))
+
+                for name in images:
+                    self.assertFalse(storage.exists(name))
+
+    def test_image_cleanup_rollback(self):
+        """
+        Replacing an image or deleting a module type in a transaction which is rolled back should keep the file.
+        """
+        for operation in ('replace', 'delete'):
+            with self.subTest(operation=operation):
+                module_type = self._create_module_type(model=operation)
+                pk = module_type.pk
+                original_name = module_type.front_image.name
+                storage = module_type.front_image.storage
+
+                with self.captureOnCommitCallbacks(execute=True), self.assertRaises(RuntimeError):
+                    with transaction.atomic():
+                        if operation == 'replace':
+                            module_type.front_image = create_test_image('replacement.png')
+                            module_type.save()
+                        else:
+                            module_type.delete()
+                        raise RuntimeError('Roll back the transaction')
+
+                self.assertEqual(ModuleType.objects.get(pk=pk).front_image.name, original_name)
+                self.assertTrue(storage.exists(original_name))
+
+
 class RackTypeTestCase(TestCase):
 
     @classmethod

+ 70 - 1
netbox/dcim/tests/test_views.py

@@ -1,6 +1,7 @@
 import csv
 import datetime
 import json
+import tempfile
 from decimal import Decimal
 from io import StringIO
 from unittest.mock import patch
@@ -35,7 +36,7 @@ from netbox.choices import (
 from netbox.exporters import get_exporter
 from tenancy.models import Tenant
 from users.models import ObjectPermission, Owner, User
-from utilities.testing import ViewTestCases, create_tags, create_test_device, post_data
+from utilities.testing import ViewTestCases, create_tags, create_test_device, create_test_image, post_data
 from wireless.models import WirelessLAN
 
 
@@ -1623,6 +1624,58 @@ class ModuleTypeTestCase(ViewTestCases.PrimaryObjectViewTestCase):
             f"{module_types[0].id},test model",
         )
 
+    def test_module_type_detail_includes_images(self):
+        """
+        The module type view should show the front and rear images.
+        """
+        self.add_permissions('dcim.view_moduletype')
+        module_type = self._get_queryset().first()
+        module_type.front_image = 'moduletype-images/front.png'
+        module_type.rear_image = 'moduletype-images/rear.png'
+        module_type.save()
+
+        response = self.client.get(module_type.get_absolute_url())
+
+        self.assertContains(response, f'src="{module_type.front_image.url}"')
+        self.assertContains(response, f'src="{module_type.rear_image.url}"')
+
+    def test_bulk_delete_rollback_keeps_images(self):
+        """
+        A bulk delete which fails on an in-use module type should keep the image files of the others.
+        """
+        self.add_permissions('dcim.delete_moduletype')
+        manufacturer = Manufacturer.objects.get(slug='manufacturer-1')
+
+        with tempfile.TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root):
+            module_type = ModuleType.objects.create(
+                manufacturer=manufacturer,
+                model='Module Type A',
+                front_image=create_test_image('front.png'),
+                rear_image=create_test_image('rear.png'),
+            )
+            in_use_type = ModuleType.objects.create(manufacturer=manufacturer, model='Module Type B')
+            device = create_test_device('Device 1')
+            module_bay = ModuleBay.objects.create(device=device, name='Module Bay 1')
+            Module.objects.create(device=device, module_bay=module_bay, module_type=in_use_type)
+            images = (module_type.front_image.name, module_type.rear_image.name)
+            storage = module_type.front_image.storage
+
+            # The view deletes in the default ordering, so the type with images goes before the in-use type
+            pk_list = [module_type.pk, in_use_type.pk]
+            self.assertEqual(list(ModuleType.objects.filter(pk__in=pk_list).values_list('pk', flat=True)), pk_list)
+            data = {
+                'pk': pk_list,
+                'confirm': True,
+                '_confirm': True,  # Form button
+            }
+            with self.captureOnCommitCallbacks(execute=True):
+                response = self.client.post(self._get_url('bulk_delete'), data)
+
+            self.assertHttpStatus(response, 302)
+            self.assertTrue(ModuleType.objects.filter(pk=module_type.pk).exists())
+            for name in images:
+                self.assertTrue(storage.exists(name))
+
     def test_bulk_update_objects_with_permission(self):
         self.add_permissions(
             'dcim.add_consoleporttemplate',
@@ -3617,6 +3670,22 @@ class ModuleTestCase(
 
         self.assertContains(response, 'Module Type Profile 1')
 
+    def test_module_detail_includes_module_type_images(self):
+        """
+        The module view should show the front and rear images of its module type.
+        """
+        self.add_permissions('dcim.view_module')
+        module = self._get_queryset().first()
+        module_type = module.module_type
+        module_type.front_image = 'moduletype-images/front.png'
+        module_type.rear_image = 'moduletype-images/rear.png'
+        module_type.save()
+
+        response = self.client.get(module.get_absolute_url())
+
+        self.assertContains(response, f'src="{module_type.front_image.url}"')
+        self.assertContains(response, f'src="{module_type.rear_image.url}"')
+
     @tag('regression')
     def test_module_detail_renders_module_type_attribute_lists(self):
         self.add_permissions(

+ 2 - 0
netbox/dcim/ui/panels.py

@@ -250,6 +250,8 @@ class ModuleTypePanel(panels.ObjectAttributesPanel):
     module_bay_types = attrs.RelatedObjectListAttr(
         'module_bay_types', label=_('Bay Type Compatibility'), linkify=True
     )
+    front_image = attrs.ImageAttr('front_image')
+    rear_image = attrs.ImageAttr('rear_image')
 
 
 class PlatformPanel(panels.NestedGroupObjectPanel):

+ 69 - 3
netbox/netbox/tests/test_views.py

@@ -10,9 +10,9 @@ from django.test import Client, TransactionTestCase, override_settings, tag
 from django.urls import reverse
 from django.utils import timezone
 
-from core.models import DataFile, DataSource, ObjectChange
+from core.models import DataFile, DataSource, ObjectChange, ObjectType
 from dcim.choices import DeviceStatusChoices, InterfaceTypeChoices, SiteStatusChoices
-from dcim.models import Device, DeviceRole, DeviceType, Interface, Manufacturer, Site, VirtualChassis
+from dcim.models import Device, DeviceRole, DeviceType, Interface, Manufacturer, ModuleType, Site, VirtualChassis
 from dcim.tables import SiteTable
 from extras.events import enqueue_event
 from extras.models import ImageAttachment
@@ -25,7 +25,7 @@ from netbox.constants import EMPTY_TABLE_TEXT
 from netbox.search.backends import search_backend
 from netbox.views import generic
 from users.constants import TOKEN_PREFIX
-from users.models import Token, User
+from users.models import ObjectPermission, Token, User
 from utilities.exceptions import AbortRequest
 from utilities.testing import TestCase
 from utilities.views import get_action_url
@@ -337,6 +337,12 @@ class MediaViewTestCase(TestCase):
             manufacturer=manufacturer,
             front_image='devicetype-images/front.jpg',
         )
+        cls.module_type = ModuleType.objects.create(
+            model='Module Type 1',
+            manufacturer=manufacturer,
+            front_image='moduletype-images/front.jpg',
+            rear_image='moduletype-images/rear.jpg',
+        )
 
     def test_media_login_required(self):
         url = reverse('media', kwargs={'path': 'foo.txt'})
@@ -404,6 +410,66 @@ class MediaViewTestCase(TestCase):
         response = self.client.get(url)
         self.assertHttpStatus(response, 404)
 
+    def test_module_type_with_permission(self):
+        """
+        A user who can view a module type should receive both of its images.
+        """
+        self.add_permissions('dcim.view_moduletype')
+        for image in (self.module_type.front_image, self.module_type.rear_image):
+            url = reverse('media', kwargs={'path': image.name})
+            with patch('netbox.views.misc.serve', return_value=HttpResponse(status=200)):
+                response = self.client.get(url)
+            self.assertHttpStatus(response, 200)
+            self.assertEqual(response['Content-Security-Policy'], "sandbox; default-src 'none'")
+            self.assertEqual(response['X-Content-Type-Options'], "nosniff")
+
+    def test_module_type_without_permission(self):
+        """
+        A user who cannot view a module type should get a 404 for its image.
+        """
+        # serve() is stubbed because it would 404 anyway, the fixture files not being on disk
+        url = reverse('media', kwargs={'path': self.module_type.front_image.name})
+        with patch('netbox.views.misc.serve', return_value=HttpResponse(status=200)) as serve:
+            response = self.client.get(url)
+        self.assertHttpStatus(response, 404)
+        serve.assert_not_called()
+
+    def test_module_type_traversal_without_permission(self):
+        """
+        A traversal path that normalizes to a module type image should still be denied.
+        """
+        traversal_path = 'foo/../' + self.module_type.front_image.name
+        url = reverse('media', kwargs={'path': traversal_path})
+        with patch('netbox.views.misc.serve', return_value=HttpResponse(status=200)) as serve:
+            response = self.client.get(url)
+        self.assertHttpStatus(response, 404)
+        serve.assert_not_called()
+
+    def test_module_type_with_constrained_permission(self):
+        """
+        A constrained view permission should serve only the images of the module types it covers.
+        """
+        hidden_type = ModuleType.objects.create(
+            model='Module Type 2',
+            manufacturer=self.module_type.manufacturer,
+            front_image='moduletype-images/hidden.jpg',
+        )
+        obj_perm = ObjectPermission(
+            name='Test permission',
+            actions=['view'],
+            constraints={'pk': self.module_type.pk},
+        )
+        obj_perm.save()
+        obj_perm.users.add(self.user)
+        obj_perm.object_types.add(ObjectType.objects.get_for_model(ModuleType))
+
+        with patch('netbox.views.misc.serve', return_value=HttpResponse(status=200)) as serve:
+            response = self.client.get(reverse('media', kwargs={'path': self.module_type.front_image.name}))
+            self.assertHttpStatus(response, 200)
+            response = self.client.get(reverse('media', kwargs={'path': hidden_type.front_image.name}))
+            self.assertHttpStatus(response, 404)
+        serve.assert_called_once()
+
 
 class DeleteAtomicityMixin:
     """

+ 6 - 1
netbox/netbox/views/misc.py

@@ -18,7 +18,7 @@ from django.views.static import serve
 from django_tables2 import RequestConfig
 from packaging import version
 
-from dcim.models import DeviceType
+from dcim.models import DeviceType, ModuleType
 from extras.constants import DEFAULT_DASHBOARD
 from extras.dashboard.utils import get_dashboard, get_default_dashboard
 from extras.models import ImageAttachment
@@ -158,6 +158,11 @@ class MediaView(TokenConditionalLoginRequiredMixin, View):
                 Q(front_image=path) | Q(rear_image=path)
             ).exists():
                 raise Http404
+        elif path.startswith('moduletype-images/'):
+            if not ModuleType.objects.restrict(request.user, 'view').filter(
+                Q(front_image=path) | Q(rear_image=path)
+            ).exists():
+                raise Http404
 
         response = serve(request, path, document_root=settings.MEDIA_ROOT)
         response['Content-Security-Policy'] = "sandbox; default-src 'none'"

+ 20 - 0
netbox/templates/dcim/panels/module_type.html

@@ -27,5 +27,25 @@
         </td>
       </tr>
     {% endfor %}
+    <tr>
+      <th scope="row">{% trans "Front image" %}</th>
+      <td>
+        {% if object.module_type.front_image %}
+          {% include "ui/attrs/image.html" with value=object.module_type.front_image load_lazy=True decoding="async" only %}
+        {% else %}
+          {{ ''|placeholder }}
+        {% endif %}
+      </td>
+    </tr>
+    <tr>
+      <th scope="row">{% trans "Rear image" %}</th>
+      <td>
+        {% if object.module_type.rear_image %}
+          {% include "ui/attrs/image.html" with value=object.module_type.rear_image load_lazy=True decoding="async" only %}
+        {% else %}
+          {{ ''|placeholder }}
+        {% endif %}
+      </td>
+    </tr>
   </table>
 {% endblock panel_content %}