widgets.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import datetime
  2. from django.forms.widgets import Widget
  3. class DatePickerWidget(Widget):
  4. template_name = 'widgets/date-picker.html'
  5. n_weeks = 5
  6. def get_context(self, name, value, attrs):
  7. context = super().get_context(name, value, attrs)
  8. # get first day of the week
  9. today = datetime.date.today()
  10. context['widget']['today'] = today
  11. first_day_of_week = today - datetime.timedelta(days=today.weekday())
  12. # get the weekdays
  13. weekdays = []
  14. for i in range(7):
  15. weekdays.append((first_day_of_week + datetime.timedelta(days=i)).strftime('%A')[0])
  16. context['widget']['weekdays'] = weekdays
  17. # for the next weeks
  18. weeks = []
  19. for i in range(self.n_weeks):
  20. date = first_day_of_week + datetime.timedelta(days=i*7)
  21. week = {
  22. 'days': [],
  23. 'month': date.strftime('%b'),
  24. 'year': date.strftime('%Y'),
  25. }
  26. for j in range(7):
  27. day = {
  28. 'date': date + datetime.timedelta(days=j),
  29. 'day': (date + datetime.timedelta(days=j)).strftime('%d'),
  30. }
  31. week['days'].append(day)
  32. weeks.append(week)
  33. context['widget']['weeks'] = weeks
  34. return context
  35. def value_from_datadict(self, data, files, name):
  36. dates = []
  37. for day in self.GetValidDates():
  38. if data.get(f"date_{day.strftime('%Y-%m-%d')}") == "on":
  39. dates.append(day)
  40. return dates
  41. def value_omitted_from_data(self, data, files, name):
  42. return not any(
  43. (data.get(f"date_{day.strftime('%Y-%m-%d')}") == "on")
  44. for day in self.GetValidDates()
  45. )
  46. def GetValidDates(self):
  47. today = datetime.date.today()
  48. return [
  49. (today + datetime.timedelta(days=i))
  50. for i in range(7*self.n_weeks)
  51. ]