boundfield.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import datetime
  2. import re
  3. from django.forms.utils import flatatt, pretty_name
  4. from django.forms.widgets import Textarea, TextInput
  5. from django.utils.functional import cached_property
  6. from django.utils.html import conditional_escape, format_html, html_safe
  7. from django.utils.safestring import mark_safe
  8. from django.utils.translation import gettext_lazy as _
  9. __all__ = ('BoundField',)
  10. @html_safe
  11. class BoundField:
  12. "A Field plus data"
  13. def __init__(self, form, field, name):
  14. self.form = form
  15. self.field = field
  16. self.name = name
  17. self.html_name = form.add_prefix(name)
  18. self.html_initial_name = form.add_initial_prefix(name)
  19. self.html_initial_id = form.add_initial_prefix(self.auto_id)
  20. if self.field.label is None:
  21. self.label = pretty_name(name)
  22. else:
  23. self.label = self.field.label
  24. self.help_text = field.help_text or ''
  25. def __str__(self):
  26. """Render this field as an HTML widget."""
  27. if self.field.show_hidden_initial:
  28. return self.as_widget() + self.as_hidden(only_initial=True)
  29. return self.as_widget()
  30. @cached_property
  31. def subwidgets(self):
  32. """
  33. Most widgets yield a single subwidget, but others like RadioSelect and
  34. CheckboxSelectMultiple produce one subwidget for each choice.
  35. This property is cached so that only one database query occurs when
  36. rendering ModelChoiceFields.
  37. """
  38. id_ = self.field.widget.attrs.get('id') or self.auto_id
  39. attrs = {'id': id_} if id_ else {}
  40. attrs = self.build_widget_attrs(attrs)
  41. return [
  42. BoundWidget(self.field.widget, widget, self.form.renderer)
  43. for widget in self.field.widget.subwidgets(self.html_name, self.value(), attrs=attrs)
  44. ]
  45. def __bool__(self):
  46. # BoundField evaluates to True even if it doesn't have subwidgets.
  47. return True
  48. def __iter__(self):
  49. return iter(self.subwidgets)
  50. def __len__(self):
  51. return len(self.subwidgets)
  52. def __getitem__(self, idx):
  53. # Prevent unnecessary reevaluation when accessing BoundField's attrs
  54. # from templates.
  55. if not isinstance(idx, (int, slice)):
  56. raise TypeError(
  57. 'BoundField indices must be integers or slices, not %s.'
  58. % type(idx).__name__
  59. )
  60. return self.subwidgets[idx]
  61. @property
  62. def errors(self):
  63. """
  64. Return an ErrorList (empty if there are no errors) for this field.
  65. """
  66. return self.form.errors.get(self.name, self.form.error_class())
  67. def as_widget(self, widget=None, attrs=None, only_initial=False):
  68. """
  69. Render the field by rendering the passed widget, adding any HTML
  70. attributes passed as attrs. If a widget isn't specified, use the
  71. field's default widget.
  72. """
  73. widget = widget or self.field.widget
  74. if self.field.localize:
  75. widget.is_localized = True
  76. attrs = attrs or {}
  77. attrs = self.build_widget_attrs(attrs, widget)
  78. if self.auto_id and 'id' not in widget.attrs:
  79. attrs.setdefault('id', self.html_initial_id if only_initial else self.auto_id)
  80. return widget.render(
  81. name=self.html_initial_name if only_initial else self.html_name,
  82. value=self.value(),
  83. attrs=attrs,
  84. renderer=self.form.renderer,
  85. )
  86. def as_text(self, attrs=None, **kwargs):
  87. """
  88. Return a string of HTML for representing this as an <input type="text">.
  89. """
  90. return self.as_widget(TextInput(), attrs, **kwargs)
  91. def as_textarea(self, attrs=None, **kwargs):
  92. """Return a string of HTML for representing this as a <textarea>."""
  93. return self.as_widget(Textarea(), attrs, **kwargs)
  94. def as_hidden(self, attrs=None, **kwargs):
  95. """
  96. Return a string of HTML for representing this as an <input type="hidden">.
  97. """
  98. return self.as_widget(self.field.hidden_widget(), attrs, **kwargs)
  99. @property
  100. def data(self):
  101. """
  102. Return the data for this BoundField, or None if it wasn't given.
  103. """
  104. return self.form._field_data_value(self.field, self.html_name)
  105. def value(self):
  106. """
  107. Return the value for this BoundField, using the initial value if
  108. the form is not bound or the data otherwise.
  109. """
  110. data = self.initial
  111. if self.form.is_bound:
  112. data = self.field.bound_data(self.data, data)
  113. return self.field.prepare_value(data)
  114. def label_tag(self, contents=None, attrs=None, label_suffix=None):
  115. """
  116. Wrap the given contents in a <label>, if the field has an ID attribute.
  117. contents should be mark_safe'd to avoid HTML escaping. If contents
  118. aren't given, use the field's HTML-escaped label.
  119. If attrs are given, use them as HTML attributes on the <label> tag.
  120. label_suffix overrides the form's label_suffix.
  121. """
  122. contents = contents or self.label
  123. if label_suffix is None:
  124. label_suffix = (self.field.label_suffix if self.field.label_suffix is not None
  125. else self.form.label_suffix)
  126. # Only add the suffix if the label does not end in punctuation.
  127. # Translators: If found as last label character, these punctuation
  128. # characters will prevent the default label_suffix to be appended to the label
  129. if label_suffix and contents and contents[-1] not in _(':?.!'):
  130. contents = format_html('{}{}', contents, label_suffix)
  131. widget = self.field.widget
  132. id_ = widget.attrs.get('id') or self.auto_id
  133. if id_:
  134. id_for_label = widget.id_for_label(id_)
  135. if id_for_label:
  136. attrs = {**(attrs or {}), 'for': id_for_label}
  137. if self.field.required and hasattr(self.form, 'required_css_class'):
  138. attrs = attrs or {}
  139. if 'class' in attrs:
  140. attrs['class'] += ' ' + self.form.required_css_class
  141. else:
  142. attrs['class'] = self.form.required_css_class
  143. attrs = flatatt(attrs) if attrs else ''
  144. contents = format_html('<label{}>{}</label>', attrs, contents)
  145. else:
  146. contents = conditional_escape(contents)
  147. return mark_safe(contents)
  148. def css_classes(self, extra_classes=None):
  149. """
  150. Return a string of space-separated CSS classes for this field.
  151. """
  152. if hasattr(extra_classes, 'split'):
  153. extra_classes = extra_classes.split()
  154. extra_classes = set(extra_classes or [])
  155. if self.errors and hasattr(self.form, 'error_css_class'):
  156. extra_classes.add(self.form.error_css_class)
  157. if self.field.required and hasattr(self.form, 'required_css_class'):
  158. extra_classes.add(self.form.required_css_class)
  159. return ' '.join(extra_classes)
  160. @property
  161. def is_hidden(self):
  162. """Return True if this BoundField's widget is hidden."""
  163. return self.field.widget.is_hidden
  164. @property
  165. def auto_id(self):
  166. """
  167. Calculate and return the ID attribute for this BoundField, if the
  168. associated Form has specified auto_id. Return an empty string otherwise.
  169. """
  170. auto_id = self.form.auto_id # Boolean or string
  171. if auto_id and '%s' in str(auto_id):
  172. return auto_id % self.html_name
  173. elif auto_id:
  174. return self.html_name
  175. return ''
  176. @property
  177. def id_for_label(self):
  178. """
  179. Wrapper around the field widget's `id_for_label` method.
  180. Useful, for example, for focusing on this field regardless of whether
  181. it has a single widget or a MultiWidget.
  182. """
  183. widget = self.field.widget
  184. id_ = widget.attrs.get('id') or self.auto_id
  185. return widget.id_for_label(id_)
  186. @cached_property
  187. def initial(self):
  188. data = self.form.get_initial_for_field(self.field, self.name)
  189. # If this is an auto-generated default date, nix the microseconds for
  190. # standardized handling. See #22502.
  191. if (isinstance(data, (datetime.datetime, datetime.time)) and
  192. not self.field.widget.supports_microseconds):
  193. data = data.replace(microsecond=0)
  194. return data
  195. def build_widget_attrs(self, attrs, widget=None):
  196. widget = widget or self.field.widget
  197. attrs = dict(attrs) # Copy attrs to avoid modifying the argument.
  198. if widget.use_required_attribute(self.initial) and self.field.required and self.form.use_required_attribute:
  199. attrs['required'] = True
  200. if self.field.disabled:
  201. attrs['disabled'] = True
  202. return attrs
  203. @property
  204. def widget_type(self):
  205. return re.sub(r'widget$|input$', '', self.field.widget.__class__.__name__.lower())
  206. @html_safe
  207. class BoundWidget:
  208. """
  209. A container class used for iterating over widgets. This is useful for
  210. widgets that have choices. For example, the following can be used in a
  211. template:
  212. {% for radio in myform.beatles %}
  213. <label for="{{ radio.id_for_label }}">
  214. {{ radio.choice_label }}
  215. <span class="radio">{{ radio.tag }}</span>
  216. </label>
  217. {% endfor %}
  218. """
  219. def __init__(self, parent_widget, data, renderer):
  220. self.parent_widget = parent_widget
  221. self.data = data
  222. self.renderer = renderer
  223. def __str__(self):
  224. return self.tag(wrap_label=True)
  225. def tag(self, wrap_label=False):
  226. context = {'widget': {**self.data, 'wrap_label': wrap_label}}
  227. return self.parent_widget._render(self.template_name, context, self.renderer)
  228. @property
  229. def template_name(self):
  230. if 'template_name' in self.data:
  231. return self.data['template_name']
  232. return self.parent_widget.template_name
  233. @property
  234. def id_for_label(self):
  235. return 'id_%s_%s' % (self.data['name'], self.data['index'])
  236. @property
  237. def choice_label(self):
  238. return self.data['label']