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

59 lines
2.0 KiB
Python
Raw Normal View History

2021-09-28 10:44:53 -04:00
from django import forms
from django.utils.translation import gettext_lazy as _
2021-09-28 10:44:53 -04:00
from extras.choices import DurationChoices
from utilities.forms import BootstrapMixin
from utilities.forms.widgets import DateTimePicker, NumberWithOptions
from utilities.utils import local_now
2021-09-28 10:44:53 -04:00
__all__ = (
'ScriptForm',
)
class ScriptForm(BootstrapMixin, forms.Form):
_commit = forms.BooleanField(
required=False,
initial=True,
label=_("Commit changes"),
help_text=_("Commit changes to the database (uncheck for a dry-run)")
2021-09-28 10:44:53 -04:00
)
2022-09-18 15:06:28 +02:00
_schedule_at = forms.DateTimeField(
required=False,
widget=DateTimePicker(),
label=_("Schedule at"),
help_text=_("Schedule execution of script to a set time"),
2022-09-18 15:06:28 +02:00
)
_interval = forms.IntegerField(
required=False,
min_value=1,
label=_("Recurs every"),
widget=NumberWithOptions(
options=DurationChoices
),
help_text=_("Interval at which this script is re-run (in minutes)")
)
2021-09-28 10:44:53 -04:00
def __init__(self, *args, scheduling_enabled=True, **kwargs):
2021-09-28 10:44:53 -04:00
super().__init__(*args, **kwargs)
2022-12-12 15:27:37 -05:00
# Annotate the current system time for reference
now = local_now().strftime('%Y-%m-%d %H:%M:%S')
self.fields['_schedule_at'].help_text += _(' (current time: <strong>{now}</strong>)').format(now=now)
2022-12-12 15:27:37 -05:00
# Remove scheduling fields if scheduling is disabled
if not scheduling_enabled:
self.fields.pop('_schedule_at')
self.fields.pop('_interval')
2021-09-28 10:44:53 -04:00
def clean(self):
scheduled_time = self.cleaned_data.get('_schedule_at')
if scheduled_time and scheduled_time < local_now():
raise forms.ValidationError(_('Scheduled time must be in the future.'))
# When interval is used without schedule at, schedule for the current time
if self.cleaned_data.get('_interval') and not scheduled_time:
self.cleaned_data['_schedule_at'] = local_now()
return self.cleaned_data