scripts.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from django import forms
  2. from django.utils.translation import gettext_lazy as _
  3. from extras.choices import DurationChoices
  4. from utilities.forms.widgets import DateTimePicker, NumberWithOptions
  5. from utilities.utils import local_now
  6. __all__ = (
  7. 'ScriptForm',
  8. )
  9. class ScriptForm(forms.Form):
  10. _commit = forms.BooleanField(
  11. required=False,
  12. initial=True,
  13. label=_("Commit changes"),
  14. help_text=_("Commit changes to the database (uncheck for a dry-run)")
  15. )
  16. _schedule_at = forms.DateTimeField(
  17. required=False,
  18. widget=DateTimePicker(),
  19. label=_("Schedule at"),
  20. help_text=_("Schedule execution of script to a set time"),
  21. )
  22. _interval = forms.IntegerField(
  23. required=False,
  24. min_value=1,
  25. label=_("Recurs every"),
  26. widget=NumberWithOptions(
  27. options=DurationChoices
  28. ),
  29. help_text=_("Interval at which this script is re-run (in minutes)")
  30. )
  31. def __init__(self, *args, scheduling_enabled=True, **kwargs):
  32. super().__init__(*args, **kwargs)
  33. # Annotate the current system time for reference
  34. now = local_now().strftime('%Y-%m-%d %H:%M:%S')
  35. self.fields['_schedule_at'].help_text += _(' (current time: <strong>{now}</strong>)').format(now=now)
  36. # Remove scheduling fields if scheduling is disabled
  37. if not scheduling_enabled:
  38. self.fields.pop('_schedule_at')
  39. self.fields.pop('_interval')
  40. def clean(self):
  41. scheduled_time = self.cleaned_data.get('_schedule_at')
  42. if scheduled_time and scheduled_time < local_now():
  43. raise forms.ValidationError(_('Scheduled time must be in the future.'))
  44. # When interval is used without schedule at, schedule for the current time
  45. if self.cleaned_data.get('_interval') and not scheduled_time:
  46. self.cleaned_data['_schedule_at'] = local_now()
  47. return self.cleaned_data