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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import re
  2. import six
  3. from django import forms
  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.encoding import force_text
  9. from django.utils.safestring import mark_safe
  10. try:
  11. from django.utils.html import format_html
  12. except ImportError:
  13. # Django 1.4 compatibility
  14. from oscar.core.compat import format_html
  15. class ImageInput(FileInput):
  16. """
  17. Widget providing a input element for file uploads based on the
  18. Django ``FileInput`` element. It hides the actual browser-specific
  19. input element and shows the available image for images that have
  20. been previously uploaded. Selecting the image will open the file
  21. dialog and allow for selecting a new or replacing image file.
  22. """
  23. template_name = 'partials/image_input_widget.html'
  24. attrs = {'accept': 'image/*'}
  25. def render(self, name, value, attrs=None):
  26. """
  27. Render the ``input`` field based on the defined ``template_name``. The
  28. image URL is take from *value* and is provided to the template as
  29. ``image_url`` context variable relative to ``MEDIA_URL``. Further
  30. attributes for the ``input`` element are provide in ``input_attrs`` and
  31. contain parameters specified in *attrs* and *name*.
  32. If *value* contains no valid image URL an empty string will be provided
  33. in the context.
  34. """
  35. if value is None:
  36. value = ''
  37. final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
  38. if value != '':
  39. # Only add the 'value' attribute if a value is non-empty.
  40. final_attrs['value'] = force_text(self._format_value(value))
  41. image_url = final_attrs.get('value', '')
  42. return render_to_string(self.template_name, Context({
  43. 'input_attrs': flatatt(final_attrs),
  44. 'image_url': image_url,
  45. 'image_id': "%s-image" % final_attrs['id'],
  46. }))
  47. class WYSIWYGTextArea(forms.Textarea):
  48. def __init__(self, *args, **kwargs):
  49. kwargs.setdefault('attrs', {})
  50. kwargs['attrs'].setdefault('class', '')
  51. kwargs['attrs']['class'] += ' wysiwyg'
  52. super(WYSIWYGTextArea, self).__init__(*args, **kwargs)
  53. def datetime_format_to_js_date_format(format):
  54. """
  55. Convert a Python datetime format to a date format suitable for use with JS
  56. date pickers
  57. """
  58. converted = format
  59. replacements = {
  60. '%Y': 'yy',
  61. '%m': 'mm',
  62. '%d': 'dd',
  63. '%H:%M': '',
  64. }
  65. for search, replace in six.iteritems(replacements):
  66. converted = converted.replace(search, replace)
  67. return converted.strip()
  68. def datetime_format_to_js_time_format(format):
  69. """
  70. Convert a Python datetime format to a time format suitable for use with JS
  71. date pickers
  72. """
  73. converted = format
  74. replacements = {
  75. '%Y': '',
  76. '%m': '',
  77. '%d': '',
  78. '%H': 'HH',
  79. '%M': 'mm',
  80. }
  81. for search, replace in six.iteritems(replacements):
  82. converted = converted.replace(search, replace)
  83. converted = re.sub('[-/][^%]', '', converted)
  84. return converted.strip()
  85. def add_js_formats(widget):
  86. """
  87. Set data attributes for date and time format on a widget
  88. """
  89. attrs = {
  90. 'data-dateFormat': datetime_format_to_js_date_format(
  91. widget.format),
  92. 'data-timeFormat': datetime_format_to_js_time_format(
  93. widget.format)
  94. }
  95. widget.attrs.update(attrs)
  96. class DatePickerInput(forms.DateInput):
  97. """
  98. DatePicker input that uses the jQuery UI datepicker. Data attributes are
  99. used to pass the date format to the JS
  100. """
  101. def __init__(self, *args, **kwargs):
  102. super(DatePickerInput, self).__init__(*args, **kwargs)
  103. add_js_formats(self)
  104. class DateTimePickerInput(forms.DateTimeInput):
  105. # Build a widget which uses the locale datetime format but without seconds.
  106. # We also use data attributes to pass these formats to the JS datepicker.
  107. def __init__(self, *args, **kwargs):
  108. include_seconds = kwargs.pop('include_seconds', False)
  109. super(DateTimePickerInput, self).__init__(*args, **kwargs)
  110. if not include_seconds:
  111. self.format = re.sub(':?%S', '', self.format)
  112. add_js_formats(self)
  113. class AdvancedSelect(forms.Select):
  114. """
  115. Customised Select widget that allows a list of disabled values to be passed
  116. to the constructor. Django's default Select widget doesn't allow this so
  117. we have to override the render_option method and add a section that checks
  118. for whether the widget is disabled.
  119. """
  120. def __init__(self, attrs=None, choices=(), disabled_values=()):
  121. self.disabled_values = set(force_text(v) for v in disabled_values)
  122. super(AdvancedSelect, self).__init__(attrs, choices)
  123. def render_option(self, selected_choices, option_value, option_label):
  124. option_value = force_text(option_value)
  125. if option_value in self.disabled_values:
  126. selected_html = mark_safe(' disabled="disabled"')
  127. elif option_value in selected_choices:
  128. selected_html = mark_safe(' selected="selected"')
  129. if not self.allow_multiple_selected:
  130. # Only allow for a single selection.
  131. selected_choices.remove(option_value)
  132. else:
  133. selected_html = ''
  134. return format_html('<option value="{0}"{1}>{2}</option>',
  135. option_value,
  136. selected_html,
  137. force_text(option_label))