chrono/chrono/manager/widgets.py

88 lines
3.1 KiB
Python

# chrono - agendas system
# Copyright (C) 2016-2019 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.forms.fields import SplitDateTimeField
from django.forms.widgets import SelectMultiple, SplitDateTimeWidget, TimeInput
from django.utils.safestring import mark_safe
class SplitDateTimeWidget(SplitDateTimeWidget):
template_name = 'chrono/splitdatetime.html'
def __init__(self, *args, **kwargs):
kwargs['time_format'] = '%H:%M'
kwargs['date_format'] = '%Y-%m-%d'
super().__init__(*args, **kwargs)
class SplitDateTimeField(SplitDateTimeField):
widget = SplitDateTimeWidget
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# fix for django<2.1, see https://code.djangoproject.com/ticket/28882
for f in self.fields:
if self.disabled:
f.disabled = True
def clean(self, value):
# fix for django<2.1, see https://code.djangoproject.com/ticket/28882
if self.disabled and not isinstance(value, list):
value = self.widget.decompress(value)
return super().clean(value)
class TimeWidget(TimeInput):
"""
TimeWidget is a widget for time selection, it uses the HTML5 "time"
input type and has a bit of a fallback mechanism with the presence
of the pattern attribute in case a standard text input is used.
"""
input_type = 'time'
def __init__(self, **kwargs):
super(TimeWidget, self).__init__(**kwargs)
self.attrs['step'] = '300' # 5 minutes
self.attrs['pattern'] = '[0-9]{2}:[0-9]{2}'
class WeekdaysWidget(SelectMultiple):
def render(self, name, value, attrs=None, choices=(), renderer=None):
s = []
value = value or []
for choice_id, choice_label in self.choices:
s.append(
'<li><label><input type="checkbox" '
' name="%(name)s-%(choice_id)s" %(checked)s>'
'<span>%(choice_label)s</span></label></li>'
% {
'name': name,
'checked': 'checked' if choice_id in value else '',
'choice_id': choice_id,
'choice_label': choice_label,
}
)
return mark_safe('<ul id="%(id)s">' % attrs + '\n'.join(s) + '</ul>')
def value_from_datadict(self, data, files, name):
choices = []
for choice_id, choice_label in self.choices:
if data.get('%s-%s' % (name, choice_id)):
choices.append(choice_id)
return choices