Skip to content

Commit

Permalink
Fixes netbox-community#15812: Add DateVar for scripts to allow much e…
Browse files Browse the repository at this point in the history
…asier date input
  • Loading branch information
JCWasmx86 committed Apr 23, 2024
1 parent 85db007 commit 34ea801
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
4 changes: 4 additions & 0 deletions docs/customization/custom-scripts.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,10 @@ An IPv4 or IPv6 network with a mask. Returns a `netaddr.IPNetwork` object. Two a
* `min_prefix_length` - Minimum length of the mask
* `max_prefix_length` - Maximum length of the mask

### DateVar

A date. Returns a `datetime.Date` object.

## Running Custom Scripts

!!! note
Expand Down
13 changes: 13 additions & 0 deletions netbox/extras/scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@
from utilities.exceptions import AbortScript, AbortTransaction
from utilities.forms import add_blank_choice
from utilities.forms.fields import DynamicModelChoiceField, DynamicModelMultipleChoiceField
from utilities.forms.widgets import DatePicker
from .context_managers import event_tracking
from .forms import ScriptForm

__all__ = (
'BaseScript',
'BooleanVar',
'ChoiceVar',
'DateVar',
'FileVar',
'IntegerVar',
'IPAddressVar',
Expand Down Expand Up @@ -172,6 +174,17 @@ def __init__(self, choices, *args, **kwargs):
self.field_attrs['choices'] = add_blank_choice(choices)


class DateVar(ScriptVariable):
"""
A date.
"""
form_field = forms.DateField

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.form_field.widget = DatePicker()


class MultiChoiceVar(ScriptVariable):
"""
Like ChoiceVar, but allows for the selection of multiple choices.
Expand Down
17 changes: 17 additions & 0 deletions netbox/extras/tests/test_scripts.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import tempfile
from datetime import date

from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
Expand Down Expand Up @@ -322,3 +323,19 @@ class TestScript(Script):
form = TestScript().as_form(data, None)
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['var1'], IPNetwork(data['var1']))

def test_datevar(self):

class TestScript(Script):

var1 = DateVar()
var2 = DateVar(required=False)

# Validate valid data
input_date = date(2024, 4, 1)
data = {'var1': input_date}
form = TestScript().as_form(data, None)
self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['var1'], input_date)
# Validate required=False works for this Var type
self.assertEqual(form.cleaned_data['var2'], None)

0 comments on commit 34ea801

Please sign in to comment.