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

Fixes #23608: Preserve custom colors in the color select widget

Arthur 1 неделя назад
Родитель
Сommit
491c8720d8

+ 37 - 2
netbox/extras/tests/test_forms.py

@@ -14,9 +14,18 @@ from extras.choices import CustomFieldTypeChoices, EventRuleActionChoices
 from extras.forms import SavedFilterForm, TableConfigBulkEditForm, TableConfigForm
 from extras.forms.bulk_import import EventRuleImportForm
 from extras.forms.filtersets import EventRuleFilterForm
-from extras.forms.model_forms import CustomFieldChoiceSetForm, EventRuleForm
+from extras.forms.model_forms import CustomFieldChoiceSetForm, EventRuleForm, TagForm
 from extras.forms.scripts import ScriptFileForm
-from extras.models import CustomField, CustomFieldChoiceSet, EventRule, NotificationGroup, Script, ScriptModule, Webhook
+from extras.models import (
+    CustomField,
+    CustomFieldChoiceSet,
+    EventRule,
+    NotificationGroup,
+    Script,
+    ScriptModule,
+    Tag,
+    Webhook,
+)
 from netbox.event_rules import EventRuleAction, register_event_rule_action
 from netbox.registry import registry
 from utilities.forms.widgets import HTMXSelect
@@ -693,3 +702,29 @@ class EventRuleImportFormTestCase(TestCase):
         self.assertFalse(form.is_valid())
         self.assertIn(NON_FIELD_ERRORS, form.errors)
         self.assertIn('Bad action_data for test', form.errors[NON_FIELD_ERRORS])
+
+
+class TagFormTestCase(TestCase):
+
+    def test_edit_tag_with_custom_color(self):
+        """
+        A Tag with a color outside the predefined ColorChoices can be edited without losing its color.
+        """
+        tag = Tag.objects.create(name='Tag 1', slug='tag-1', color='e20074')
+
+        # The current color must be rendered as the selected option
+        form = TagForm(instance=tag)
+        self.assertInHTML(
+            '<option value="e20074" selected>e20074</option>',
+            str(form['color'])
+        )
+
+        form = TagForm(instance=tag, data={
+            'name': 'Tag 1 renamed',
+            'slug': 'tag-1',
+            'color': 'e20074',
+            'weight': 1000,
+        })
+        self.assertTrue(form.is_valid(), form.errors)
+        tag = form.save()
+        self.assertEqual(tag.color, 'e20074')

+ 10 - 0
netbox/utilities/forms/widgets/select.py

@@ -94,6 +94,16 @@ class ColorSelect(forms.Select):
         super().__init__(*args, **kwargs)
         self.attrs['class'] = 'color-select'
 
+    def optgroups(self, name, value, attrs=None):
+        groups = super().optgroups(name, value, attrs)
+        # Render a custom (non-predefined) color as a selected option so it isn't lost on submission
+        known_values = {str(choice[0]) for choice in self.choices}
+        for color in value:
+            if color and color not in known_values:
+                index = len(groups)
+                groups.append((None, [self.create_option(name, color, color, True, index)], index))
+        return groups
+
 
 class HTMXSelect(Select):
     """

+ 19 - 2
netbox/utilities/tests/test_forms.py

@@ -8,7 +8,7 @@ from django.test import TestCase, override_settings
 from django.utils.html import escape
 
 from dcim.models import Rack, Site
-from netbox.choices import ImportFormatChoices
+from netbox.choices import ColorChoices, ImportFormatChoices
 from utilities.choices import Choice, ChoiceSet
 from utilities.forms.bulk_import import BulkImportForm
 from utilities.forms.fields import ChoiceField, MultipleChoiceField, TypedChoiceField
@@ -31,7 +31,7 @@ from utilities.forms.utils import (
     get_field_value,
     parse_numeric_range,
 )
-from utilities.forms.widgets.select import AvailableOptions, HTMXSelect, Select, SelectedOptions
+from utilities.forms.widgets.select import AvailableOptions, ColorSelect, HTMXSelect, Select, SelectedOptions
 
 
 class ExpandIPNetworkTestCase(TestCase):
@@ -1155,3 +1155,20 @@ class DescriptionSelectTestCase(TestCase):
         self.assertTrue(calls)
         # And descriptions are still collected as normal
         self.assertEqual(field.widget.descriptions, {self.ExampleChoices.FOO: 'Description of foo'})
+
+
+class ColorSelectTestCase(TestCase):
+
+    def test_predefined_color_selected(self):
+        html = ColorSelect().render('color', ColorChoices.COLOR_RED)
+        self.assertInHTML(f'<option value="{ColorChoices.COLOR_RED}" selected>Red</option>', html)
+        self.assertEqual(html.count(f'value="{ColorChoices.COLOR_RED}"'), 1)
+
+    def test_custom_color_rendered_as_selected_option(self):
+        html = ColorSelect().render('color', 'e20074')
+        self.assertInHTML('<option value="e20074" selected>e20074</option>', html)
+
+    def test_empty_value_adds_no_option(self):
+        widget = ColorSelect()
+        html = widget.render('color', None)
+        self.assertEqual(html.count('<option'), len(widget.choices))