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/>.
import datetime
from django.forms.widgets import DateTimeInput, TimeInput, SelectMultiple
from django.utils import dateparse
from django.utils.safestring import mark_safe
class DateTimeWidget(DateTimeInput):
template_name = 'chrono/widget_datetime.html'
def format_value(self, value):
if value:
x = {
'date': value.date().strftime('%Y-%m-%d'),
'time': value.time().strftime('%H:%M'),
}
return x
return None
def value_from_datadict(self, data, files, name):
date_string = data.get(name + '$date')
time_string = data.get(name + '$time')
if not date_string or not time_string:
return None
date_value = dateparse.parse_date(date_string)
time_value = dateparse.parse_time(time_string)
if not date_value or not time_value:
return None
return datetime.datetime.combine(date_value, time_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