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.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. from django.core.files.uploadedfile import InMemoryUploadedFile
  2. import re
  3. import six
  4. from django import forms
  5. from django.forms.util import flatatt
  6. from django.forms.widgets import FileInput
  7. from django.template import Context
  8. from django.template.loader import render_to_string
  9. from django.utils.encoding import force_text
  10. from django.utils.safestring import mark_safe
  11. try:
  12. from django.utils.html import format_html
  13. except ImportError:
  14. # Django 1.4 compatibility
  15. from oscar.core.compat import format_html
  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 six.iteritems(replacements):
  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 six.iteritems(replacements):
  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. if not include_seconds:
  112. self.format = re.sub(':?%S', '', self.format)
  113. add_js_formats(self)
  114. class AdvancedSelect(forms.Select):
  115. """
  116. Customised Select widget that allows a list of disabled values to be passed
  117. to the constructor. Django's default Select widget doesn't allow this so
  118. we have to override the render_option method and add a section that checks
  119. for whether the widget is disabled.
  120. """
  121. def __init__(self, attrs=None, choices=(), disabled_values=()):
  122. self.disabled_values = set(force_text(v) for v in disabled_values)
  123. super(AdvancedSelect, self).__init__(attrs, choices)
  124. def render_option(self, selected_choices, option_value, option_label):
  125. option_value = force_text(option_value)
  126. if option_value in self.disabled_values:
  127. selected_html = mark_safe(' disabled="disabled"')
  128. elif option_value in selected_choices:
  129. selected_html = mark_safe(' selected="selected"')
  130. if not self.allow_multiple_selected:
  131. # Only allow for a single selection.
  132. selected_choices.remove(option_value)
  133. else:
  134. selected_html = ''
  135. return format_html(u'<option value="{0}"{1}>{2}</option>',
  136. option_value,
  137. selected_html,
  138. force_text(option_label))