You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

widgets.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import re
  2. from django import forms
  3. from django.core.files.uploadedfile import InMemoryUploadedFile
  4. from django.forms.util import flatatt
  5. from django.forms.widgets import FileInput
  6. from django.template import Context
  7. from django.template.loader import render_to_string
  8. from django.utils import formats, six
  9. from django.utils.six.moves import filter
  10. from django.utils.six.moves import map
  11. from django.utils.encoding import force_text
  12. from django.utils.html import format_html
  13. from django.utils.safestring import mark_safe
  14. class ImageInput(FileInput):
  15. """
  16. Widget providing a input element for file uploads based on the
  17. Django ``FileInput`` element. It hides the actual browser-specific
  18. input element and shows the available image for images that have
  19. been previously uploaded. Selecting the image will open the file
  20. dialog and allow for selecting a new or replacing image file.
  21. """
  22. template_name = 'partials/image_input_widget.html'
  23. attrs = {'accept': 'image/*'}
  24. def render(self, name, value, attrs=None):
  25. """
  26. Render the ``input`` field based on the defined ``template_name``. The
  27. image URL is take from *value* and is provided to the template as
  28. ``image_url`` context variable relative to ``MEDIA_URL``. Further
  29. attributes for the ``input`` element are provide in ``input_attrs`` and
  30. contain parameters specified in *attrs* and *name*.
  31. If *value* contains no valid image URL an empty string will be provided
  32. in the context.
  33. """
  34. final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
  35. if not value or isinstance(value, InMemoryUploadedFile):
  36. # can't display images that aren't stored
  37. image_url = ''
  38. else:
  39. image_url = final_attrs['value'] = force_text(
  40. self._format_value(value))
  41. return render_to_string(self.template_name, Context({
  42. 'input_attrs': flatatt(final_attrs),
  43. 'image_url': image_url,
  44. 'image_id': "%s-image" % final_attrs['id'],
  45. }))
  46. class WYSIWYGTextArea(forms.Textarea):
  47. def __init__(self, *args, **kwargs):
  48. kwargs.setdefault('attrs', {})
  49. kwargs['attrs'].setdefault('class', '')
  50. kwargs['attrs']['class'] += ' wysiwyg'
  51. super(WYSIWYGTextArea, self).__init__(*args, **kwargs)
  52. def datetime_format_to_js_date_format(format):
  53. """
  54. Convert a Python datetime format to a date format suitable for use with
  55. the JS date picker we use.
  56. """
  57. format = format.split()[0]
  58. return datetime_format_to_js_datetime_format(format)
  59. def datetime_format_to_js_time_format(format):
  60. """
  61. Convert a Python datetime format to a time format suitable for use with the
  62. JS time picker we use.
  63. """
  64. try:
  65. format = format.split()[1]
  66. except IndexError:
  67. pass
  68. converted = format
  69. replacements = {
  70. '%H': 'hh',
  71. '%I': 'HH',
  72. '%M': 'ii',
  73. '%S': 'ss',
  74. }
  75. for search, replace in replacements.items():
  76. converted = converted.replace(search, replace)
  77. return converted.strip()
  78. def datetime_format_to_js_datetime_format(format):
  79. """
  80. Convert a Python datetime format to a time format suitable for use with
  81. the datetime picker we use, http://www.malot.fr/bootstrap-datetimepicker/.
  82. """
  83. converted = format
  84. replacements = {
  85. '%Y': 'yyyy',
  86. '%y': 'yy',
  87. '%m': 'mm',
  88. '%d': 'dd',
  89. '%H': 'hh',
  90. '%I': 'HH',
  91. '%M': 'ii',
  92. '%S': 'ss',
  93. }
  94. for search, replace in replacements.items():
  95. converted = converted.replace(search, replace)
  96. return converted.strip()
  97. class TimePickerInput(forms.TimeInput):
  98. """
  99. A widget that passes the date format to the JS date picker in a data
  100. attribute.
  101. """
  102. def render(self, name, value, attrs=None):
  103. format = self.format
  104. if hasattr(self, 'manual_format'):
  105. # For django <= 1.6.5, see
  106. # https://code.djangoproject.com/ticket/21173
  107. if self.is_localized and not self.manual_format:
  108. format = force_text(
  109. formats.get_format('DATE_INPUT_FORMATS')[0])
  110. else:
  111. # For django >= 1.7
  112. format = format or formats.get_format(self.format_key)[0]
  113. input = super(TimePickerInput, self).render(name, value, attrs)
  114. attrs = {'data-oscarWidget': 'time',
  115. 'data-timeFormat':
  116. datetime_format_to_js_time_format(format),
  117. }
  118. div = format_html('<div class="input-append date"{}>', flatatt(attrs))
  119. return mark_safe('{div}'
  120. ' {input}'
  121. ' <span class="add-on">'
  122. ' <i class="icon-time"></i>'
  123. ' </span>'
  124. '</div>'
  125. .format(div=div, input=input))
  126. class DatePickerInput(forms.DateInput):
  127. """
  128. A widget that passes the date format to the JS date picker in a data
  129. attribute.
  130. """
  131. def render(self, name, value, attrs=None):
  132. format = self.format
  133. if hasattr(self, 'manual_format'):
  134. # For django <= 1.6.5, see
  135. # https://code.djangoproject.com/ticket/21173
  136. if self.is_localized and not self.manual_format:
  137. format = force_text(
  138. formats.get_format('DATE_INPUT_FORMATS')[0])
  139. else:
  140. # For django >= 1.7
  141. format = format or formats.get_format(self.format_key)[0]
  142. input = super(DatePickerInput, self).render(name, value, attrs)
  143. attrs = {'data-oscarWidget': 'date',
  144. 'data-dateFormat':
  145. datetime_format_to_js_date_format(format),
  146. }
  147. div = format_html('<div class="input-append date"{}>', flatatt(attrs))
  148. return mark_safe('{div}'
  149. ' {input}'
  150. ' <span class="add-on">'
  151. ' <i class="icon-calendar"></i>'
  152. ' </span>'
  153. '</div>'
  154. .format(div=div, input=input))
  155. class DateTimePickerInput(forms.DateTimeInput):
  156. """
  157. A widget that passes the datetime format to the JS datetime picker in a
  158. data attribute.
  159. It also removes seconds by default. However this only works with widgets
  160. without localize=True.
  161. For localized widgets refer to
  162. https://docs.djangoproject.com/en/1.6/topics/i18n/formatting/#creating-custom-format-files # noqa
  163. instead to override the format.
  164. """
  165. def __init__(self, *args, **kwargs):
  166. include_seconds = kwargs.pop('include_seconds', False)
  167. super(DateTimePickerInput, self).__init__(*args, **kwargs)
  168. if not include_seconds and self.format:
  169. self.format = re.sub(':?%S', '', self.format)
  170. def render(self, name, value, attrs=None):
  171. format = self.format
  172. if hasattr(self, 'manual_format'):
  173. # For django <= 1.6.5, see
  174. # https://code.djangoproject.com/ticket/21173
  175. if self.is_localized and not self.manual_format:
  176. format = force_text(
  177. formats.get_format('DATETIME_INPUT_FORMATS')[0])
  178. else:
  179. # For django >= 1.7
  180. format = format or formats.get_format(self.format_key)[0]
  181. input = super(DateTimePickerInput, self).render(name, value, attrs)
  182. attrs = {'data-oscarWidget': 'datetime',
  183. 'data-datetimeFormat':
  184. datetime_format_to_js_datetime_format(format),
  185. }
  186. div = format_html('<div class="input-append date"{}>', flatatt(attrs))
  187. return mark_safe('{div}'
  188. ' {input}'
  189. ' <span class="add-on">'
  190. ' <i class="icon-calendar"></i>'
  191. ' </span>'
  192. '</div>'
  193. .format(div=div, input=input))
  194. class AdvancedSelect(forms.Select):
  195. """
  196. Customised Select widget that allows a list of disabled values to be passed
  197. to the constructor. Django's default Select widget doesn't allow this so
  198. we have to override the render_option method and add a section that checks
  199. for whether the widget is disabled.
  200. """
  201. def __init__(self, attrs=None, choices=(), disabled_values=()):
  202. self.disabled_values = set(force_text(v) for v in disabled_values)
  203. super(AdvancedSelect, self).__init__(attrs, choices)
  204. def render_option(self, selected_choices, option_value, option_label):
  205. option_value = force_text(option_value)
  206. if option_value in self.disabled_values:
  207. selected_html = mark_safe(' disabled="disabled"')
  208. elif option_value in selected_choices:
  209. selected_html = mark_safe(' selected="selected"')
  210. if not self.allow_multiple_selected:
  211. # Only allow for a single selection.
  212. selected_choices.remove(option_value)
  213. else:
  214. selected_html = ''
  215. return format_html(u'<option value="{0}"{1}>{2}</option>',
  216. option_value,
  217. selected_html,
  218. force_text(option_label))
  219. class RemoteSelect(forms.Widget):
  220. """
  221. Somewhat reusable widget that allows AJAX lookups in combination with
  222. select2.
  223. Requires setting the URL of a lookup view either as class attribute or when
  224. constructing
  225. """
  226. is_multiple = False
  227. css = 'select2 input-xlarge'
  228. lookup_url = None
  229. def __init__(self, *args, **kwargs):
  230. if 'lookup_url' in kwargs:
  231. self.lookup_url = kwargs.pop('lookup_url')
  232. if self.lookup_url is None:
  233. raise ValueError(
  234. "RemoteSelect requires a lookup ULR")
  235. super(RemoteSelect, self).__init__(*args, **kwargs)
  236. def format_value(self, value):
  237. return six.text_type(value or '')
  238. def value_from_datadict(self, data, files, name):
  239. value = data.get(name, None)
  240. if value is None:
  241. return value
  242. else:
  243. return six.text_type(value)
  244. def render(self, name, value, attrs=None, choices=()):
  245. attrs = self.build_attrs(attrs, **{
  246. 'type': 'hidden',
  247. 'class': self.css,
  248. 'name': name,
  249. 'data-ajax-url': self.lookup_url,
  250. 'data-multiple': 'multiple' if self.is_multiple else '',
  251. 'value': self.format_value(value),
  252. 'data-required': 'required' if self.is_required else '',
  253. })
  254. return mark_safe(u'<input %s>' % flatatt(attrs))
  255. class MultipleRemoteSelect(RemoteSelect):
  256. is_multiple = True
  257. css = 'select2 input-xxlarge'
  258. def format_value(self, value):
  259. if value:
  260. return ','.join(map(six.text_type, filter(bool, value)))
  261. else:
  262. return ''
  263. def value_from_datadict(self, data, files, name):
  264. value = data.get(name, None)
  265. if value is None:
  266. return []
  267. else:
  268. return list(filter(bool, value.split(',')))