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 7.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. import re
  2. import six
  3. from six.moves import filter
  4. from six.moves import map
  5. import django
  6. from django import forms
  7. from django.core.files.uploadedfile import InMemoryUploadedFile
  8. from django.forms.util import flatatt
  9. from django.forms.widgets import FileInput
  10. from django.template import Context
  11. from django.template.loader import render_to_string
  12. from django.utils import formats
  13. from django.utils.encoding import force_text
  14. from django.utils.html import format_html
  15. from django.utils.safestring import mark_safe
  16. class ImageInput(FileInput):
  17. """
  18. Widget providing a input element for file uploads based on the
  19. Django ``FileInput`` element. It hides the actual browser-specific
  20. input element and shows the available image for images that have
  21. been previously uploaded. Selecting the image will open the file
  22. dialog and allow for selecting a new or replacing image file.
  23. """
  24. template_name = 'partials/image_input_widget.html'
  25. attrs = {'accept': 'image/*'}
  26. def render(self, name, value, attrs=None):
  27. """
  28. Render the ``input`` field based on the defined ``template_name``. The
  29. image URL is take from *value* and is provided to the template as
  30. ``image_url`` context variable relative to ``MEDIA_URL``. Further
  31. attributes for the ``input`` element are provide in ``input_attrs`` and
  32. contain parameters specified in *attrs* and *name*.
  33. If *value* contains no valid image URL an empty string will be provided
  34. in the context.
  35. """
  36. final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
  37. if not value or isinstance(value, InMemoryUploadedFile):
  38. # can't display images that aren't stored
  39. image_url = ''
  40. else:
  41. image_url = final_attrs['value'] = force_text(
  42. self._format_value(value))
  43. return render_to_string(self.template_name, Context({
  44. 'input_attrs': flatatt(final_attrs),
  45. 'image_url': image_url,
  46. 'image_id': "%s-image" % final_attrs['id'],
  47. }))
  48. class WYSIWYGTextArea(forms.Textarea):
  49. def __init__(self, *args, **kwargs):
  50. kwargs.setdefault('attrs', {})
  51. kwargs['attrs'].setdefault('class', '')
  52. kwargs['attrs']['class'] += ' wysiwyg'
  53. super(WYSIWYGTextArea, self).__init__(*args, **kwargs)
  54. def datetime_format_to_js_date_format(format):
  55. """
  56. Convert a Python datetime format to a date format suitable for use with JS
  57. date pickers
  58. """
  59. converted = format
  60. replacements = {
  61. '%Y': 'yy',
  62. '%m': 'mm',
  63. '%d': 'dd',
  64. '%H:%M': '',
  65. }
  66. for search, replace in replacements.items():
  67. converted = converted.replace(search, replace)
  68. return converted.strip()
  69. def datetime_format_to_js_time_format(format):
  70. """
  71. Convert a Python datetime format to a time format suitable for use with JS
  72. date pickers
  73. """
  74. converted = format
  75. replacements = {
  76. '%Y': '',
  77. '%m': '',
  78. '%d': '',
  79. '%H': 'HH',
  80. '%M': 'mm',
  81. }
  82. for search, replace in replacements.items():
  83. converted = converted.replace(search, replace)
  84. converted = re.sub('[-/][^%]', '', converted)
  85. return converted.strip()
  86. def add_js_formats(widget):
  87. """
  88. Set data attributes for date and time format on a widget
  89. """
  90. attrs = {
  91. 'data-dateFormat': datetime_format_to_js_date_format(
  92. widget.format),
  93. 'data-timeFormat': datetime_format_to_js_time_format(
  94. widget.format)
  95. }
  96. widget.attrs.update(attrs)
  97. class DatePickerInput(forms.DateInput):
  98. """
  99. DatePicker input that uses the jQuery UI datepicker. Data attributes are
  100. used to pass the date format to the JS
  101. """
  102. def __init__(self, *args, **kwargs):
  103. super(DatePickerInput, self).__init__(*args, **kwargs)
  104. add_js_formats(self)
  105. class DateTimePickerInput(forms.DateTimeInput):
  106. # Build a widget which uses the locale datetime format but without seconds.
  107. # We also use data attributes to pass these formats to the JS datepicker.
  108. def __init__(self, *args, **kwargs):
  109. include_seconds = kwargs.pop('include_seconds', False)
  110. super(DateTimePickerInput, self).__init__(*args, **kwargs)
  111. # Django 1.7+ has format default as 0
  112. if django.VERSION >= (1, 7):
  113. self.format = self.format or formats.get_format(self.format_key)[0]
  114. if self.format and not include_seconds:
  115. self.format = re.sub(':?%S', '', self.format)
  116. add_js_formats(self)
  117. class AdvancedSelect(forms.Select):
  118. """
  119. Customised Select widget that allows a list of disabled values to be passed
  120. to the constructor. Django's default Select widget doesn't allow this so
  121. we have to override the render_option method and add a section that checks
  122. for whether the widget is disabled.
  123. """
  124. def __init__(self, attrs=None, choices=(), disabled_values=()):
  125. self.disabled_values = set(force_text(v) for v in disabled_values)
  126. super(AdvancedSelect, self).__init__(attrs, choices)
  127. def render_option(self, selected_choices, option_value, option_label):
  128. option_value = force_text(option_value)
  129. if option_value in self.disabled_values:
  130. selected_html = mark_safe(' disabled="disabled"')
  131. elif option_value in selected_choices:
  132. selected_html = mark_safe(' selected="selected"')
  133. if not self.allow_multiple_selected:
  134. # Only allow for a single selection.
  135. selected_choices.remove(option_value)
  136. else:
  137. selected_html = ''
  138. return format_html(u'<option value="{0}"{1}>{2}</option>',
  139. option_value,
  140. selected_html,
  141. force_text(option_label))
  142. class RemoteSelect(forms.Widget):
  143. """
  144. Somewhat reusable widget that allows AJAX lookups in combination with
  145. select2.
  146. Requires setting the URL of a lookup view either as class attribute or when
  147. constructing
  148. """
  149. is_multiple = False
  150. css = 'select2 input-xlarge'
  151. lookup_url = None
  152. def __init__(self, *args, **kwargs):
  153. if 'lookup_url' in kwargs:
  154. self.lookup_url = kwargs.pop('lookup_url')
  155. if self.lookup_url is None:
  156. raise ValueError(
  157. "RemoteSelect requires a lookup ULR")
  158. super(RemoteSelect, self).__init__(*args, **kwargs)
  159. def format_value(self, value):
  160. return six.text_type(value or '')
  161. def value_from_datadict(self, data, files, name):
  162. value = data.get(name, None)
  163. if value is None:
  164. return value
  165. else:
  166. return six.text_type(value)
  167. def render(self, name, value, attrs=None, choices=()):
  168. attrs = self.build_attrs(attrs, **{
  169. 'type': 'hidden',
  170. 'class': self.css,
  171. 'name': name,
  172. 'data-ajax-url': self.lookup_url,
  173. 'data-multiple': 'multiple' if self.is_multiple else '',
  174. 'value': self.format_value(value),
  175. 'data-required': 'required' if self.is_required else '',
  176. })
  177. return mark_safe(u'<input %s>' % flatatt(attrs))
  178. class MultipleRemoteSelect(RemoteSelect):
  179. is_multiple = True
  180. css = 'select2 input-xxlarge'
  181. def format_value(self, value):
  182. if value:
  183. return ','.join(map(six.text_type, filter(bool, value)))
  184. else:
  185. return ''
  186. def value_from_datadict(self, data, files, name):
  187. value = data.get(name, None)
  188. if value is None:
  189. return []
  190. else:
  191. return list(filter(bool, value.split(',')))