|
@@ -0,0 +1,63 @@
|
|
|
|
+import datetime
|
|
|
|
+
|
|
|
|
+from django.forms.widgets import Widget
|
|
|
|
+
|
|
|
|
+class DatePickerWidget(Widget):
|
|
|
|
+ template_name = 'widgets/date-picker.html'
|
|
|
|
+
|
|
|
|
+ n_weeks = 5
|
|
|
|
+
|
|
|
|
+ def get_context(self, name, value, attrs):
|
|
|
|
+ context = super().get_context(name, value, attrs)
|
|
|
|
+
|
|
|
|
+ # get first day of the week
|
|
|
|
+ today = datetime.date.today()
|
|
|
|
+ context['widget']['today'] = today
|
|
|
|
+ first_day_of_week = today - datetime.timedelta(days=today.weekday())
|
|
|
|
+
|
|
|
|
+ # get the weekdays
|
|
|
|
+ weekdays = []
|
|
|
|
+ for i in range(7):
|
|
|
|
+ weekdays.append((first_day_of_week + datetime.timedelta(days=i)).strftime('%A')[0])
|
|
|
|
+ context['widget']['weekdays'] = weekdays
|
|
|
|
+
|
|
|
|
+ # for the next weeks
|
|
|
|
+ weeks = []
|
|
|
|
+ for i in range(self.n_weeks):
|
|
|
|
+ date = first_day_of_week + datetime.timedelta(days=i*7)
|
|
|
|
+ week = {
|
|
|
|
+ 'days': [],
|
|
|
|
+ 'month': date.strftime('%b'),
|
|
|
|
+ 'year': date.strftime('%Y'),
|
|
|
|
+ }
|
|
|
|
+ for j in range(7):
|
|
|
|
+ day = {
|
|
|
|
+ 'date': date + datetime.timedelta(days=j),
|
|
|
|
+ 'day': (date + datetime.timedelta(days=j)).strftime('%d'),
|
|
|
|
+ }
|
|
|
|
+ week['days'].append(day)
|
|
|
|
+ weeks.append(week)
|
|
|
|
+
|
|
|
|
+ context['widget']['weeks'] = weeks
|
|
|
|
+
|
|
|
|
+ return context
|
|
|
|
+
|
|
|
|
+ def value_from_datadict(self, data, files, name):
|
|
|
|
+ dates = []
|
|
|
|
+ for day in self.GetValidDates():
|
|
|
|
+ if data.get(f"date_{day.strftime('%Y-%m-%d')}") == "on":
|
|
|
|
+ dates.append(day)
|
|
|
|
+ return dates
|
|
|
|
+
|
|
|
|
+ def value_omitted_from_data(self, data, files, name):
|
|
|
|
+ return not any(
|
|
|
|
+ (data.get(f"date_{day.strftime('%Y-%m-%d')}") == "on")
|
|
|
|
+ for day in self.GetValidDates()
|
|
|
|
+ )
|
|
|
|
+
|
|
|
|
+ def GetValidDates(self):
|
|
|
|
+ today = datetime.date.today()
|
|
|
|
+ return [
|
|
|
|
+ (today + datetime.timedelta(days=i))
|
|
|
|
+ for i in range(7*self.n_weeks)
|
|
|
|
+ ]
|