scripts.py 2.0 KB

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