123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- import datetime
- import ctypes
- from django.forms.widgets import Widget
- from .models import Participant, Date, Event
- from .helpers import string2slots, get_slot_count, slots2string, slots2grid
- from django.utils.translation import gettext as _
- 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')))
- 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)
- ]
- class SlotPickerWidget(Widget):
- template_name = 'widgets/slot-picker.html'
- def get_context(self, name, value, attrs):
- context = super().get_context(name, value, attrs)
- if self.participant:
- context['widget']['grid'] = slots2grid(self.event, [self.participant], True)
- else:
- context['widget']['grid'] = slots2grid(self.event, [], True)
- return context
- def value_from_datadict(self, data, files, name):
- # create a mutable string buffer
- slots = ctypes.create_string_buffer(self.n_slots)
- # set the slots
- for i in range(self.n_slots):
- if data.get(f"slot_{i}") == "on":
- slots[i] = b'1'
- else:
- slots[i] = b'0'
- # return the slots as a string
- return slots.value
- def value_omitted_from_data(self, data, files, name):
- return False
-
- def __init__(self, *args, event, n_slots, participant, **kwargs):
- super().__init__(*args, **kwargs)
- self.event = event
- self.participant = participant
- self.n_slots = n_slots
|