Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. def datetime_format_to_js_input_mask(format):
  98. # taken from
  99. # http://stackoverflow.com/questions/15175142/how-can-i-do-multiple-substitutions-using-regex-in-python # noqa
  100. def multiple_replace(dict, text):
  101. # Create a regular expression from the dictionary keys
  102. regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
  103. # For each match, look-up corresponding value in dictionary
  104. return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)
  105. replacements = {
  106. '%Y': 'y',
  107. '%y': '99',
  108. '%m': 'm',
  109. '%d': 'd',
  110. '%H': 'h',
  111. '%I': 'h',
  112. '%M': 's',
  113. '%S': 's',
  114. }
  115. return multiple_replace(replacements, format).strip()
  116. class DateTimeWidgetMixin(object):
  117. def get_format(self):
  118. format = self.format
  119. if hasattr(self, 'manual_format'):
  120. # For django <= 1.6.5, see
  121. # https://code.djangoproject.com/ticket/21173
  122. if self.is_localized and not self.manual_format:
  123. format = force_text(formats.get_format(self.format_key)[0])
  124. else:
  125. # For django >= 1.7
  126. format = format or formats.get_format(self.format_key)[0]
  127. return format
  128. def gett_attrs(self, attrs, format):
  129. if not attrs:
  130. attrs = {}
  131. attrs['data-inputmask'] = "'mask': '{mask}'".format(
  132. mask=datetime_format_to_js_input_mask(format))
  133. return attrs
  134. class TimePickerInput(DateTimeWidgetMixin, forms.TimeInput):
  135. """
  136. A widget that passes the date format to the JS date picker in a data
  137. attribute.
  138. """
  139. format_key = 'TIME_INPUT_FORMATS'
  140. def render(self, name, value, attrs=None):
  141. format = self.get_format()
  142. input = super(TimePickerInput, self).render(
  143. name, value, self.gett_attrs(attrs, format))
  144. attrs = {'data-oscarWidget': 'time',
  145. 'data-timeFormat':
  146. datetime_format_to_js_time_format(format),
  147. }
  148. div = format_html('<div class="input-append date"{}>', flatatt(attrs))
  149. return mark_safe('{div}'
  150. ' {input}'
  151. ' <span class="add-on">'
  152. ' <i class="icon-time"></i>'
  153. ' </span>'
  154. '</div>'
  155. .format(div=div, input=input))
  156. class DatePickerInput(DateTimeWidgetMixin, forms.DateInput):
  157. """
  158. A widget that passes the date format to the JS date picker in a data
  159. attribute.
  160. """
  161. format_key = 'DATE_INPUT_FORMATS'
  162. def render(self, name, value, attrs=None):
  163. format = self.get_format()
  164. input = super(DatePickerInput, self).render(
  165. name, value, self.gett_attrs(attrs, format))
  166. attrs = {'data-oscarWidget': 'date',
  167. 'data-dateFormat':
  168. datetime_format_to_js_date_format(format),
  169. }
  170. div = format_html('<div class="input-append date"{}>', flatatt(attrs))
  171. return mark_safe('{div}'
  172. ' {input}'
  173. ' <span class="add-on">'
  174. ' <i class="icon-calendar"></i>'
  175. ' </span>'
  176. '</div>'
  177. .format(div=div, input=input))
  178. class DateTimePickerInput(DateTimeWidgetMixin, forms.DateTimeInput):
  179. """
  180. A widget that passes the datetime format to the JS datetime picker in a
  181. data attribute.
  182. It also removes seconds by default. However this only works with widgets
  183. without localize=True.
  184. For localized widgets refer to
  185. https://docs.djangoproject.com/en/1.6/topics/i18n/formatting/#creating-custom-format-files # noqa
  186. instead to override the format.
  187. """
  188. format_key = 'DATETIME_INPUT_FORMATS'
  189. def __init__(self, *args, **kwargs):
  190. include_seconds = kwargs.pop('include_seconds', False)
  191. super(DateTimePickerInput, self).__init__(*args, **kwargs)
  192. if not include_seconds and self.format:
  193. self.format = re.sub(':?%S', '', self.format)
  194. def render(self, name, value, attrs=None):
  195. format = self.get_format()
  196. input = super(DateTimePickerInput, self).render(
  197. name, value, self.gett_attrs(attrs, format))
  198. attrs = {'data-oscarWidget': 'datetime',
  199. 'data-datetimeFormat':
  200. datetime_format_to_js_datetime_format(format),
  201. }
  202. div = format_html('<div class="input-append date"{}>', flatatt(attrs))
  203. return mark_safe('{div}'
  204. ' {input}'
  205. ' <span class="add-on">'
  206. ' <i class="icon-calendar"></i>'
  207. ' </span>'
  208. '</div>'
  209. .format(div=div, input=input))
  210. class AdvancedSelect(forms.Select):
  211. """
  212. Customised Select widget that allows a list of disabled values to be passed
  213. to the constructor. Django's default Select widget doesn't allow this so
  214. we have to override the render_option method and add a section that checks
  215. for whether the widget is disabled.
  216. """
  217. def __init__(self, attrs=None, choices=(), disabled_values=()):
  218. self.disabled_values = set(force_text(v) for v in disabled_values)
  219. super(AdvancedSelect, self).__init__(attrs, choices)
  220. def render_option(self, selected_choices, option_value, option_label):
  221. option_value = force_text(option_value)
  222. if option_value in self.disabled_values:
  223. selected_html = mark_safe(' disabled="disabled"')
  224. elif option_value in selected_choices:
  225. selected_html = mark_safe(' selected="selected"')
  226. if not self.allow_multiple_selected:
  227. # Only allow for a single selection.
  228. selected_choices.remove(option_value)
  229. else:
  230. selected_html = ''
  231. return format_html(u'<option value="{0}"{1}>{2}</option>',
  232. option_value,
  233. selected_html,
  234. force_text(option_label))
  235. class RemoteSelect(forms.Widget):
  236. """
  237. Somewhat reusable widget that allows AJAX lookups in combination with
  238. select2.
  239. Requires setting the URL of a lookup view either as class attribute or when
  240. constructing
  241. """
  242. is_multiple = False
  243. css = 'select2 input-xlarge'
  244. lookup_url = None
  245. def __init__(self, *args, **kwargs):
  246. if 'lookup_url' in kwargs:
  247. self.lookup_url = kwargs.pop('lookup_url')
  248. if self.lookup_url is None:
  249. raise ValueError(
  250. "RemoteSelect requires a lookup ULR")
  251. super(RemoteSelect, self).__init__(*args, **kwargs)
  252. def format_value(self, value):
  253. return six.text_type(value or '')
  254. def value_from_datadict(self, data, files, name):
  255. value = data.get(name, None)
  256. if value is None:
  257. return value
  258. else:
  259. return six.text_type(value)
  260. def render(self, name, value, attrs=None, choices=()):
  261. attrs = self.build_attrs(attrs, **{
  262. 'type': 'hidden',
  263. 'class': self.css,
  264. 'name': name,
  265. 'data-ajax-url': self.lookup_url,
  266. 'data-multiple': 'multiple' if self.is_multiple else '',
  267. 'value': self.format_value(value),
  268. 'data-required': 'required' if self.is_required else '',
  269. })
  270. return mark_safe(u'<input %s>' % flatatt(attrs))
  271. class MultipleRemoteSelect(RemoteSelect):
  272. is_multiple = True
  273. css = 'select2 input-xxlarge'
  274. def format_value(self, value):
  275. if value:
  276. return ','.join(map(six.text_type, filter(bool, value)))
  277. else:
  278. return ''
  279. def value_from_datadict(self, data, files, name):
  280. value = data.get(name, None)
  281. if value is None:
  282. return []
  283. else:
  284. return list(filter(bool, value.split(',')))