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

Closes #8368: Enable controlling the order of custom script form fields with field_order

jeremystretch 4 лет назад
Родитель
Сommit
69eb6b11d0

+ 4 - 0
docs/customization/custom-scripts.md

@@ -77,6 +77,10 @@ This is the human-friendly names of your script. If omitted, the class name will
 
 A human-friendly description of what your script does.
 
+### `field_order`
+
+By default, script variables will be ordered in the form as they are defined in the script. `field_order` may be defined as an iterable of field names to determine the order in which variables are rendered. Any fields not included in this iterable be listed last.
+
 ### `commit_default`
 
 The checkbox to commit database changes when executing a script is checked by default. Set `commit_default` to False under the script's Meta class to leave this option unchecked by default.

+ 1 - 0
docs/release-notes/version-3.1.md

@@ -6,6 +6,7 @@
 
 * [#8275](https://github.com/netbox-community/netbox/issues/8275) - Introduce alternative ASDOT-formatted column for ASNs
 * [#8367](https://github.com/netbox-community/netbox/issues/8367) - Add ASNs to global search function
+* [#8368](https://github.com/netbox-community/netbox/issues/8368) - Enable controlling the order of custom script form fields with `field_order`
 * [#8381](https://github.com/netbox-community/netbox/issues/8381) - Add contacts to global search function
 
 ### Bug Fixes

+ 11 - 2
netbox/extras/scripts.py

@@ -296,12 +296,21 @@ class BaseScript:
 
     @classmethod
     def _get_vars(cls):
-        vars = OrderedDict()
+        vars = {}
         for name, attr in cls.__dict__.items():
             if name not in vars and issubclass(attr.__class__, ScriptVariable):
                 vars[name] = attr
 
-        return vars
+        # Order variables according to field_order
+        field_order = getattr(cls.Meta, 'field_order', None)
+        if not field_order:
+            return vars
+        ordered_vars = {
+            field: vars.pop(field) for field in field_order if field in vars
+        }
+        ordered_vars.update(vars)
+
+        return ordered_vars
 
     def run(self, data, commit):
         raise NotImplementedError("The script must define a run() method.")