Procházet zdrojové kódy

14467 change ChoiceField separator from comma to colon (#14469)

* 14467 change ChoiceField separator from comma to colon

* 14467 fix test

* 14467 fix test

* 14467 use regex for colon detection

* 14467 update tests
Arthur Hanson před 2 roky
rodič
revize
6939ae4a47

+ 4 - 3
netbox/extras/forms/model_forms.py

@@ -1,4 +1,5 @@
 import json
+import re
 
 from django import forms
 from django.conf import settings
@@ -95,8 +96,8 @@ class CustomFieldChoiceSetForm(BootstrapMixin, forms.ModelForm):
         required=False,
         help_text=mark_safe(_(
             'Enter one choice per line. An optional label may be specified for each choice by appending it with a '
-            'comma. Example:'
-        ) + ' <code>choice1,First Choice</code>')
+            'colon. Example:'
+        ) + ' <code>choice1:First Choice</code>')
     )
 
     class Meta:
@@ -107,7 +108,7 @@ class CustomFieldChoiceSetForm(BootstrapMixin, forms.ModelForm):
         data = []
         for line in self.cleaned_data['extra_choices'].splitlines():
             try:
-                value, label = line.split(',', maxsplit=1)
+                value, label = re.split(r'(?<!\\):', line, maxsplit=1)
             except ValueError:
                 value, label = line, line
             data.append((value, label))

+ 8 - 1
netbox/extras/tests/test_views.py

@@ -98,7 +98,7 @@ class CustomFieldChoiceSetTestCase(ViewTestCases.PrimaryObjectViewTestCase):
 
         cls.form_data = {
             'name': 'Choice Set X',
-            'extra_choices': '\n'.join(['X1,Choice 1', 'X2,Choice 2', 'X3,Choice 3'])
+            'extra_choices': '\n'.join(['X1:Choice 1', 'X2:Choice 2', 'X3:Choice 3'])
         }
 
         cls.csv_data = (
@@ -119,6 +119,13 @@ class CustomFieldChoiceSetTestCase(ViewTestCases.PrimaryObjectViewTestCase):
             'description': 'New description',
         }
 
+    # This is here as extra_choices field splits on colon, but is returned
+    # from DB as comma separated.
+    def assertInstanceEqual(self, instance, data, exclude=None, api=False):
+        if 'extra_choices' in data:
+            data['extra_choices'] = data['extra_choices'].replace(':', ',')
+        return super().assertInstanceEqual(instance, data, exclude, api)
+
 
 class CustomLinkTestCase(ViewTestCases.PrimaryObjectViewTestCase):
     model = CustomLink

+ 1 - 1
netbox/utilities/forms/widgets/misc.py

@@ -65,5 +65,5 @@ class ChoicesWidget(forms.Textarea):
         if not value:
             return None
         if type(value) is list:
-            return '\n'.join([f'{k},{v}' for k, v in value])
+            return '\n'.join([f'{k}:{v}' for k, v in value])
         return value