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.
 
 
 
 

228 lines
8.5 KiB

  1. from __future__ import unicode_literals
  2. import datetime
  3. from django.forms.utils import flatatt, pretty_name
  4. from django.forms.widgets import Textarea, TextInput
  5. from django.utils import six
  6. from django.utils.encoding import (
  7. force_text, python_2_unicode_compatible, smart_text,
  8. )
  9. from django.utils.html import conditional_escape, format_html, html_safe
  10. from django.utils.safestring import mark_safe
  11. from django.utils.translation import ugettext_lazy as _
  12. __all__ = ('BoundField',)
  13. UNSET = object()
  14. @html_safe
  15. @python_2_unicode_compatible
  16. class BoundField(object):
  17. "A Field plus data"
  18. def __init__(self, form, field, name):
  19. self.form = form
  20. self.field = field
  21. self.name = name
  22. self.html_name = form.add_prefix(name)
  23. self.html_initial_name = form.add_initial_prefix(name)
  24. self.html_initial_id = form.add_initial_prefix(self.auto_id)
  25. if self.field.label is None:
  26. self.label = pretty_name(name)
  27. else:
  28. self.label = self.field.label
  29. self.help_text = field.help_text or ''
  30. self._initial_value = UNSET
  31. def __str__(self):
  32. """Renders this field as an HTML widget."""
  33. if self.field.show_hidden_initial:
  34. return self.as_widget() + self.as_hidden(only_initial=True)
  35. return self.as_widget()
  36. def __iter__(self):
  37. """
  38. Yields rendered strings that comprise all widgets in this BoundField.
  39. This really is only useful for RadioSelect widgets, so that you can
  40. iterate over individual radio buttons in a template.
  41. """
  42. id_ = self.field.widget.attrs.get('id') or self.auto_id
  43. attrs = {'id': id_} if id_ else {}
  44. for subwidget in self.field.widget.subwidgets(self.html_name, self.value(), attrs):
  45. yield subwidget
  46. def __len__(self):
  47. return len(list(self.__iter__()))
  48. def __getitem__(self, idx):
  49. # Prevent unnecessary reevaluation when accessing BoundField's attrs
  50. # from templates.
  51. if not isinstance(idx, six.integer_types + (slice,)):
  52. raise TypeError
  53. return list(self.__iter__())[idx]
  54. @property
  55. def errors(self):
  56. """
  57. Returns an ErrorList for this field. Returns an empty ErrorList
  58. if there are none.
  59. """
  60. return self.form.errors.get(self.name, self.form.error_class())
  61. def as_widget(self, widget=None, attrs=None, only_initial=False):
  62. """
  63. Renders the field by rendering the passed widget, adding any HTML
  64. attributes passed as attrs. If no widget is specified, then the
  65. field's default widget will be used.
  66. """
  67. if not widget:
  68. widget = self.field.widget
  69. if self.field.localize:
  70. widget.is_localized = True
  71. attrs = attrs or {}
  72. if self.field.disabled:
  73. attrs['disabled'] = True
  74. auto_id = self.auto_id
  75. if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
  76. if not only_initial:
  77. attrs['id'] = auto_id
  78. else:
  79. attrs['id'] = self.html_initial_id
  80. if not only_initial:
  81. name = self.html_name
  82. else:
  83. name = self.html_initial_name
  84. return force_text(widget.render(name, self.value(), attrs=attrs))
  85. def as_text(self, attrs=None, **kwargs):
  86. """
  87. Returns a string of HTML for representing this as an <input type="text">.
  88. """
  89. return self.as_widget(TextInput(), attrs, **kwargs)
  90. def as_textarea(self, attrs=None, **kwargs):
  91. "Returns a string of HTML for representing this as a <textarea>."
  92. return self.as_widget(Textarea(), attrs, **kwargs)
  93. def as_hidden(self, attrs=None, **kwargs):
  94. """
  95. Returns a string of HTML for representing this as an <input type="hidden">.
  96. """
  97. return self.as_widget(self.field.hidden_widget(), attrs, **kwargs)
  98. @property
  99. def data(self):
  100. """
  101. Returns the data for this BoundField, or None if it wasn't given.
  102. """
  103. return self.field.widget.value_from_datadict(self.form.data, self.form.files, self.html_name)
  104. def value(self):
  105. """
  106. Returns the value for this BoundField, using the initial value if
  107. the form is not bound or the data otherwise.
  108. """
  109. if not self.form.is_bound:
  110. data = self.form.initial.get(self.name, self.field.initial)
  111. if callable(data):
  112. if self._initial_value is not UNSET:
  113. data = self._initial_value
  114. else:
  115. data = data()
  116. # If this is an auto-generated default date, nix the
  117. # microseconds for standardized handling. See #22502.
  118. if (isinstance(data, (datetime.datetime, datetime.time)) and
  119. not self.field.widget.supports_microseconds):
  120. data = data.replace(microsecond=0)
  121. self._initial_value = data
  122. else:
  123. data = self.field.bound_data(
  124. self.data, self.form.initial.get(self.name, self.field.initial)
  125. )
  126. return self.field.prepare_value(data)
  127. def label_tag(self, contents=None, attrs=None, label_suffix=None):
  128. """
  129. Wraps the given contents in a <label>, if the field has an ID attribute.
  130. contents should be 'mark_safe'd to avoid HTML escaping. If contents
  131. aren't given, uses the field's HTML-escaped label.
  132. If attrs are given, they're used as HTML attributes on the <label> tag.
  133. label_suffix allows overriding the form's label_suffix.
  134. """
  135. contents = contents or self.label
  136. if label_suffix is None:
  137. label_suffix = (self.field.label_suffix if self.field.label_suffix is not None
  138. else self.form.label_suffix)
  139. # Only add the suffix if the label does not end in punctuation.
  140. # Translators: If found as last label character, these punctuation
  141. # characters will prevent the default label_suffix to be appended to the label
  142. if label_suffix and contents and contents[-1] not in _(':?.!'):
  143. contents = format_html('{}{}', contents, label_suffix)
  144. widget = self.field.widget
  145. id_ = widget.attrs.get('id') or self.auto_id
  146. if id_:
  147. id_for_label = widget.id_for_label(id_)
  148. if id_for_label:
  149. attrs = dict(attrs or {}, **{'for': id_for_label})
  150. if self.field.required and hasattr(self.form, 'required_css_class'):
  151. attrs = attrs or {}
  152. if 'class' in attrs:
  153. attrs['class'] += ' ' + self.form.required_css_class
  154. else:
  155. attrs['class'] = self.form.required_css_class
  156. attrs = flatatt(attrs) if attrs else ''
  157. contents = format_html('<label{}>{}</label>', attrs, contents)
  158. else:
  159. contents = conditional_escape(contents)
  160. return mark_safe(contents)
  161. def css_classes(self, extra_classes=None):
  162. """
  163. Returns a string of space-separated CSS classes for this field.
  164. """
  165. if hasattr(extra_classes, 'split'):
  166. extra_classes = extra_classes.split()
  167. extra_classes = set(extra_classes or [])
  168. if self.errors and hasattr(self.form, 'error_css_class'):
  169. extra_classes.add(self.form.error_css_class)
  170. if self.field.required and hasattr(self.form, 'required_css_class'):
  171. extra_classes.add(self.form.required_css_class)
  172. return ' '.join(extra_classes)
  173. @property
  174. def is_hidden(self):
  175. "Returns True if this BoundField's widget is hidden."
  176. return self.field.widget.is_hidden
  177. @property
  178. def auto_id(self):
  179. """
  180. Calculates and returns the ID attribute for this BoundField, if the
  181. associated Form has specified auto_id. Returns an empty string otherwise.
  182. """
  183. auto_id = self.form.auto_id
  184. if auto_id and '%s' in smart_text(auto_id):
  185. return smart_text(auto_id) % self.html_name
  186. elif auto_id:
  187. return self.html_name
  188. return ''
  189. @property
  190. def id_for_label(self):
  191. """
  192. Wrapper around the field widget's `id_for_label` method.
  193. Useful, for example, for focusing on this field regardless of whether
  194. it has a single widget or a MultiWidget.
  195. """
  196. widget = self.field.widget
  197. id_ = widget.attrs.get('id') or self.auto_id
  198. return widget.id_for_label(id_)