reports.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from django import forms
  2. from django.utils import timezone
  3. from django.utils.translation import gettext as _
  4. from utilities.forms import BootstrapMixin, DateTimePicker, SelectDurationWidget
  5. from utilities.utils import local_now
  6. __all__ = (
  7. 'ReportForm',
  8. )
  9. class ReportForm(BootstrapMixin, forms.Form):
  10. schedule_at = forms.DateTimeField(
  11. required=False,
  12. widget=DateTimePicker(),
  13. label=_("Schedule at"),
  14. help_text=_("Schedule execution of report to a set time"),
  15. )
  16. interval = forms.IntegerField(
  17. required=False,
  18. min_value=1,
  19. label=_("Recurs every"),
  20. widget=SelectDurationWidget(),
  21. help_text=_("Interval at which this report is re-run (in minutes)")
  22. )
  23. def clean(self):
  24. scheduled_time = self.cleaned_data['schedule_at']
  25. if scheduled_time and scheduled_time < local_now():
  26. raise forms.ValidationError(_('Scheduled time must be in the future.'))
  27. # When interval is used without schedule at, raise an exception
  28. if self.cleaned_data['interval'] and not scheduled_time:
  29. self.cleaned_data['schedule_at'] = local_now()
  30. return self.cleaned_data
  31. def __init__(self, *args, **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 += f' (current time: <strong>{now}</strong>)'