1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
|
# -*- coding: utf-8 -*-
import datetime
from json import dumps as json_dumps
import logging
from django import forms
from django.forms.utils import flatatt
from django.forms.widgets import DateTimeInput
from django.utils.safestring import mark_safe
from django.utils import translation
from django.utils.html import conditional_escape
from django.utils.encoding import force_str
logger = logging.getLogger(__name__)
DATE_FORMAT = {
'fr': "dd/mm/yyyy",
'en': "yyyy/mm/dd",
}
DATE_INPUT_FORMATS = ['%d/%m/%Y', '%Y/%m/%d', '%Y-%m-%d']
class DatePicker(DateTimeInput):
class Media:
class JSFiles(object):
def __iter__(self):
yield 'js/bootstrap-datepicker.js'
lang = translation.get_language()
if lang:
lang = lang.lower()
# language name with length > 2 or containing uppercase
lang_map = {
'en-au': 'en-AU',
'en-gb': 'en-GB',
'en-us': 'en-us',
'fr-CH': 'fr-CH',
'it-ch': 'it-CH',
'nl-be': 'nl-BE',
'pt-br': 'pt-BR',
'rs-latin': 'rs-latin',
'sr-latin': 'sr-latin',
'zh-cn': 'zh-CN',
'zh-tw': 'zh-TW',
}
if len(lang) > 2:
if lang in lang_map:
lang = lang_map[lang]
else:
lang = lang.split("-")[0]
if lang not in ('en', 'en-us'):
yield 'js/locales/bootstrap-datepicker.%s.min.js' % (
lang)
js = list(JSFiles())
css = {'all': ('css/bootstrap-datepicker3.standalone.min.css',), }
# http://bootstrap-datepicker.readthedocs.org/en/stable/options.html#format
# http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
format_map = (
('dd', r'%d'),
('DD', r'%A'),
('D', r'%a'),
('MM', r'%B'),
('M', r'%b'),
('mm', r'%m'),
('yyyy', r'%Y'),
('yy', r'%y'),
)
@classmethod
def conv_datetime_format_py2js(cls, frmat):
for js, py in cls.format_map:
frmat = frmat.replace(py, js)
return frmat
@classmethod
def conv_datetime_format_js2py(cls, frmat):
for js, py in cls.format_map:
frmat = frmat.replace(js, py)
return frmat
html_template = """
<div%(div_attrs)s>
<input%(input_attrs)s/>
<span class="input-group-append">
<span class="input-group-text">
<span%(icon_attrs)s></span>
</span>
</span>
</div>"""
js_template = '''
<script>
(function() {
var callback = function() {
$(function(){$("#%(picker_id)s:has(input:not([readonly],[disabled]))").datepicker(%(options)s);});
};
callback();
})();
</script>'''
def __init__(self, attrs=None, frmat=None, options=None, div_attrs=None,
icon_attrs=None):
if not icon_attrs:
icon_attrs = {'class': 'fa fa-calendar fa-2'}
if not div_attrs:
div_attrs = {'class': 'input-group date'}
if frmat is None and options and options.get('format'):
frmat = self.conv_datetime_format_js2py(options.get('format'))
super().__init__(attrs, frmat)
if 'class' not in self.attrs:
self.attrs['class'] = 'form-control'
self.div_attrs = div_attrs and div_attrs.copy() or {}
self.icon_attrs = icon_attrs and icon_attrs.copy() or {}
self.picker_id = self.div_attrs.get('id') or None
self.options = options and options.copy() or {}
if frmat and not self.options.get('format') and not self.attrs.get(
'date-format'):
self.options['format'] = self.conv_datetime_format_py2js(frmat)
def format_value(self, value):
if not self.options.get('format'):
logger.debug('datepicker: format not defined')
return str(value)
py_format = self.conv_datetime_format_js2py(self.options['format'])
if not hasattr(value, 'strftime'):
value = str(value)
try:
value = datetime.datetime.strptime(value, '%Y-%m-%d')
except ValueError:
logger.debug('datepicker: cannot extract date from %s' % value)
return str(value)
value = value.strftime(py_format)
return value
def render(self, name, value, attrs=None, renderer=None):
if value is None:
value = ''
extra_attrs = dict()
extra_attrs['type'] = self.input_type
extra_attrs['name'] = name
input_attrs = self.build_attrs(attrs, extra_attrs)
if value != '':
# Only add the 'value' attribute if a value is non-empty.
input_attrs['value'] = force_str(self.format_value(value))
input_attrs = {key: conditional_escape(val)
for key, val in input_attrs.items()}
if not self.picker_id:
self.picker_id = (
input_attrs.get('id', '') + '_pickers'
).replace(' ', '_')
self.div_attrs['id'] = self.picker_id
picker_id = conditional_escape(self.picker_id)
div_attrs = {key: conditional_escape(val)
for key, val in self.div_attrs.items()}
icon_attrs = {key: conditional_escape(val)
for key, val in self.icon_attrs.items()}
html = self.html_template % dict(div_attrs=flatatt(div_attrs),
input_attrs=flatatt(input_attrs),
icon_attrs=flatatt(icon_attrs))
js = self.js_template % dict(
picker_id=picker_id, options=json_dumps(self.options or {}))
return mark_safe(force_str(html + js))
class DateField(forms.DateField):
widget = DatePicker
input_formats = DATE_INPUT_FORMATS
|