1
0
mirror of https://github.com/netbox-community/netbox.git synced 2024-05-10 07:54:54 +00:00

Closes #3594: Add ChoiceVar for custom scripts

This commit is contained in:
Jeremy Stretch
2019-10-23 15:59:27 -04:00
parent 95fec1a87c
commit c7d8083ac6
4 changed files with 65 additions and 0 deletions

View File

@@ -24,6 +24,7 @@ from .signals import purge_changelog
__all__ = [
'BaseScript',
'BooleanVar',
'ChoiceVar',
'FileVar',
'IntegerVar',
'IPNetworkVar',
@@ -133,6 +134,27 @@ class BooleanVar(ScriptVariable):
self.field_attrs['required'] = False
class ChoiceVar(ScriptVariable):
"""
Select one of several predefined static choices, passed as a list of two-tuples. Example:
color = ChoiceVar(
choices=(
('#ff0000', 'Red'),
('#00ff00', 'Green'),
('#0000ff', 'Blue')
)
)
"""
form_field = forms.ChoiceField
def __init__(self, choices, *args, **kwargs):
super().__init__(*args, **kwargs)
# Set field choices
self.field_attrs['choices'] = choices
class ObjectVar(ScriptVariable):
"""
NetBox object representation. The provided QuerySet will determine the choices available.

View File

@@ -99,6 +99,31 @@ class ScriptVariablesTest(TestCase):
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['var1'], False)
def test_choicevar(self):
CHOICES = (
('ff0000', 'Red'),
('00ff00', 'Green'),
('0000ff', 'Blue')
)
class TestScript(Script):
var1 = ChoiceVar(
choices=CHOICES
)
# Validate valid choice
data = {'var1': CHOICES[0][0]}
form = TestScript().as_form(data)
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['var1'], CHOICES[0][0])
# Validate invalid choices
data = {'var1': 'taupe'}
form = TestScript().as_form(data)
self.assertFalse(form.is_valid())
def test_objectvar(self):
class TestScript(Script):