boundfield.py 9.9 KB

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