scripts.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from django import forms
  2. from django.utils.translation import gettext as _
  3. from utilities.forms import BootstrapMixin, DateTimePicker, SelectDurationWidget
  4. from utilities.utils import local_now
  5. __all__ = (
  6. 'ScriptForm',
  7. )
  8. class ScriptForm(BootstrapMixin, forms.Form):
  9. _commit = forms.BooleanField(
  10. required=False,
  11. initial=True,
  12. label=_("Commit changes"),
  13. help_text=_("Commit changes to the database (uncheck for a dry-run)")
  14. )
  15. _schedule_at = forms.DateTimeField(
  16. required=False,
  17. widget=DateTimePicker(),
  18. label=_("Schedule at"),
  19. help_text=_("Schedule execution of script to a set time"),
  20. )
  21. _interval = forms.IntegerField(
  22. required=False,
  23. min_value=1,
  24. label=_("Recurs every"),
  25. widget=SelectDurationWidget(),
  26. help_text=_("Interval at which this script is re-run (in minutes)")
  27. )
  28. def __init__(self, *args, **kwargs):
  29. super().__init__(*args, **kwargs)
  30. # Annotate the current system time for reference
  31. now = local_now().strftime('%Y-%m-%d %H:%M:%S')
  32. self.fields['_schedule_at'].help_text += f' (current time: <strong>{now}</strong>)'
  33. # Move _commit and _schedule_at to the end of the form
  34. schedule_at = self.fields.pop('_schedule_at')
  35. interval = self.fields.pop('_interval')
  36. commit = self.fields.pop('_commit')
  37. self.fields['_schedule_at'] = schedule_at
  38. self.fields['_interval'] = interval
  39. self.fields['_commit'] = commit
  40. def clean__schedule_at(self):
  41. scheduled_time = self.cleaned_data['_schedule_at']
  42. if scheduled_time and scheduled_time < timezone.now():
  43. raise forms.ValidationError(_('Scheduled time must be in the future.'))
  44. return scheduled_time
  45. @property
  46. def requires_input(self):
  47. """
  48. A boolean indicating whether the form requires user input (ignore the built-in fields).
  49. """
  50. return bool(len(self.fields) > 3)