boundfield.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. import re
  2. from django.core.exceptions import ValidationError
  3. from django.forms.utils import RenderableFieldMixin, pretty_name
  4. from django.forms.widgets import MultiWidget, Textarea, TextInput
  5. from django.utils.functional import cached_property
  6. from django.utils.html import format_html, html_safe
  7. from django.utils.translation import gettext_lazy as _
  8. __all__ = ("BoundField",)
  9. class BoundField(RenderableFieldMixin):
  10. "A Field plus data"
  11. def __init__(self, form, field, name):
  12. self.form = form
  13. self.field = field
  14. self.name = name
  15. self.html_name = form.add_prefix(name)
  16. self.html_initial_name = form.add_initial_prefix(name)
  17. self.html_initial_id = form.add_initial_prefix(self.auto_id)
  18. if self.field.label is None:
  19. self.label = pretty_name(name)
  20. else:
  21. self.label = self.field.label
  22. self.help_text = field.help_text or ""
  23. self.renderer = form.renderer
  24. @cached_property
  25. def subwidgets(self):
  26. """
  27. Most widgets yield a single subwidget, but others like RadioSelect and
  28. CheckboxSelectMultiple produce one subwidget for each choice.
  29. This property is cached so that only one database query occurs when
  30. rendering ModelChoiceFields.
  31. """
  32. id_ = self.field.widget.attrs.get("id") or self.auto_id
  33. attrs = {"id": id_} if id_ else {}
  34. attrs = self.build_widget_attrs(attrs)
  35. return [
  36. BoundWidget(self.field.widget, widget, self.form.renderer)
  37. for widget in self.field.widget.subwidgets(
  38. self.html_name, self.value(), attrs=attrs
  39. )
  40. ]
  41. def __bool__(self):
  42. # BoundField evaluates to True even if it doesn't have subwidgets.
  43. return True
  44. def __iter__(self):
  45. return iter(self.subwidgets)
  46. def __len__(self):
  47. return len(self.subwidgets)
  48. def __getitem__(self, idx):
  49. # Prevent unnecessary reevaluation when accessing BoundField's attrs
  50. # from templates.
  51. if not isinstance(idx, (int, slice)):
  52. raise TypeError(
  53. "BoundField indices must be integers or slices, not %s."
  54. % type(idx).__name__
  55. )
  56. return self.subwidgets[idx]
  57. @property
  58. def errors(self):
  59. """
  60. Return an ErrorList (empty if there are no errors) for this field.
  61. """
  62. return self.form.errors.get(
  63. self.name, self.form.error_class(renderer=self.form.renderer)
  64. )
  65. @property
  66. def template_name(self):
  67. return self.field.template_name or self.form.renderer.field_template_name
  68. def get_context(self):
  69. return {"field": self}
  70. def as_widget(self, widget=None, attrs=None, only_initial=False):
  71. """
  72. Render the field by rendering the passed widget, adding any HTML
  73. attributes passed as attrs. If a widget isn't specified, use the
  74. field's default widget.
  75. """
  76. widget = widget or self.field.widget
  77. if self.field.localize:
  78. widget.is_localized = True
  79. attrs = attrs or {}
  80. attrs = self.build_widget_attrs(attrs, widget)
  81. if self.auto_id and "id" not in widget.attrs:
  82. attrs.setdefault(
  83. "id", self.html_initial_id if only_initial else self.auto_id
  84. )
  85. if only_initial and self.html_initial_name in self.form.data:
  86. # Propagate the hidden initial value.
  87. value = self.form._widget_data_value(
  88. self.field.hidden_widget(),
  89. self.html_initial_name,
  90. )
  91. else:
  92. value = self.value()
  93. return widget.render(
  94. name=self.html_initial_name if only_initial else self.html_name,
  95. value=value,
  96. attrs=attrs,
  97. renderer=self.form.renderer,
  98. )
  99. def as_text(self, attrs=None, **kwargs):
  100. """
  101. Return a string of HTML for representing this as an
  102. <input type="text">.
  103. """
  104. return self.as_widget(TextInput(), attrs, **kwargs)
  105. def as_textarea(self, attrs=None, **kwargs):
  106. """Return a string of HTML for representing this as a <textarea>."""
  107. return self.as_widget(Textarea(), attrs, **kwargs)
  108. def as_hidden(self, attrs=None, **kwargs):
  109. """
  110. Return a string of HTML for representing this as an
  111. <input type="hidden">.
  112. """
  113. return self.as_widget(self.field.hidden_widget(), attrs, **kwargs)
  114. @property
  115. def data(self):
  116. """
  117. Return the data for this BoundField, or None if it wasn't given.
  118. """
  119. return self.form._widget_data_value(self.field.widget, self.html_name)
  120. def value(self):
  121. """
  122. Return the value for this BoundField, using the initial value if
  123. the form is not bound or the data otherwise.
  124. """
  125. data = self.initial
  126. if self.form.is_bound:
  127. data = self.field.bound_data(self.data, data)
  128. return self.field.prepare_value(data)
  129. def _has_changed(self):
  130. field = self.field
  131. if field.show_hidden_initial:
  132. hidden_widget = field.hidden_widget()
  133. initial_value = self.form._widget_data_value(
  134. hidden_widget,
  135. self.html_initial_name,
  136. )
  137. try:
  138. initial_value = field.to_python(initial_value)
  139. except ValidationError:
  140. # Always assume data has changed if validation fails.
  141. return True
  142. else:
  143. initial_value = self.initial
  144. return field.has_changed(initial_value, self.data)
  145. def label_tag(self, contents=None, attrs=None, label_suffix=None, tag=None):
  146. """
  147. Wrap the given contents in a <label>, if the field has an ID attribute.
  148. contents should be mark_safe'd to avoid HTML escaping. If contents
  149. aren't given, use the field's HTML-escaped label.
  150. If attrs are given, use them as HTML attributes on the <label> tag.
  151. label_suffix overrides the form's label_suffix.
  152. """
  153. contents = contents or self.label
  154. if label_suffix is None:
  155. label_suffix = (
  156. self.field.label_suffix
  157. if self.field.label_suffix is not None
  158. else self.form.label_suffix
  159. )
  160. # Only add the suffix if the label does not end in punctuation.
  161. # Translators: If found as last label character, these punctuation
  162. # characters will prevent the default label_suffix to be appended to
  163. # the label
  164. if label_suffix and contents and contents[-1] not in _(":?.!"):
  165. contents = format_html("{}{}", contents, label_suffix)
  166. widget = self.field.widget
  167. id_ = widget.attrs.get("id") or self.auto_id
  168. if id_:
  169. id_for_label = widget.id_for_label(id_)
  170. if id_for_label:
  171. attrs = attrs or {}
  172. if tag != "legend":
  173. attrs = {**attrs, "for": id_for_label}
  174. if self.field.required and hasattr(self.form, "required_css_class"):
  175. attrs = attrs or {}
  176. if "class" in attrs:
  177. attrs["class"] += " " + self.form.required_css_class
  178. else:
  179. attrs["class"] = self.form.required_css_class
  180. context = {
  181. "field": self,
  182. "label": contents,
  183. "attrs": attrs,
  184. "use_tag": bool(id_),
  185. "tag": tag or "label",
  186. }
  187. return self.form.render(self.form.template_name_label, context)
  188. def legend_tag(self, contents=None, attrs=None, label_suffix=None):
  189. """
  190. Wrap the given contents in a <legend>, if the field has an ID
  191. attribute. Contents should be mark_safe'd to avoid HTML escaping. If
  192. contents aren't given, use the field's HTML-escaped label.
  193. If attrs are given, use them as HTML attributes on the <legend> tag.
  194. label_suffix overrides the form's label_suffix.
  195. """
  196. return self.label_tag(contents, attrs, label_suffix, tag="legend")
  197. def css_classes(self, extra_classes=None):
  198. """
  199. Return a string of space-separated CSS classes for this field.
  200. """
  201. if hasattr(extra_classes, "split"):
  202. extra_classes = extra_classes.split()
  203. extra_classes = set(extra_classes or [])
  204. if self.errors and hasattr(self.form, "error_css_class"):
  205. extra_classes.add(self.form.error_css_class)
  206. if self.field.required and hasattr(self.form, "required_css_class"):
  207. extra_classes.add(self.form.required_css_class)
  208. return " ".join(extra_classes)
  209. @property
  210. def is_hidden(self):
  211. """Return True if this BoundField's widget is hidden."""
  212. return self.field.widget.is_hidden
  213. @property
  214. def auto_id(self):
  215. """
  216. Calculate and return the ID attribute for this BoundField, if the
  217. associated Form has specified auto_id. Return an empty string
  218. otherwise.
  219. """
  220. auto_id = self.form.auto_id # Boolean or string
  221. if auto_id and "%s" in str(auto_id):
  222. return auto_id % self.html_name
  223. elif auto_id:
  224. return self.html_name
  225. return ""
  226. @property
  227. def id_for_label(self):
  228. """
  229. Wrapper around the field widget's `id_for_label` method.
  230. Useful, for example, for focusing on this field regardless of whether
  231. it has a single widget or a MultiWidget.
  232. """
  233. widget = self.field.widget
  234. id_ = widget.attrs.get("id") or self.auto_id
  235. return widget.id_for_label(id_)
  236. @cached_property
  237. def initial(self):
  238. return self.form.get_initial_for_field(self.field, self.name)
  239. def build_widget_attrs(self, attrs, widget=None):
  240. widget = widget or self.field.widget
  241. attrs = dict(attrs) # Copy attrs to avoid modifying the argument.
  242. if (
  243. widget.use_required_attribute(self.initial)
  244. and self.field.required
  245. and self.form.use_required_attribute
  246. ):
  247. # MultiValueField has require_all_fields: if False, fall back
  248. # on subfields.
  249. if (
  250. hasattr(self.field, "require_all_fields")
  251. and not self.field.require_all_fields
  252. and isinstance(self.field.widget, MultiWidget)
  253. ):
  254. for subfield, subwidget in zip(self.field.fields, widget.widgets):
  255. subwidget.attrs["required"] = (
  256. subwidget.use_required_attribute(self.initial)
  257. and subfield.required
  258. )
  259. else:
  260. attrs["required"] = True
  261. if self.field.disabled:
  262. attrs["disabled"] = True
  263. if not widget.is_hidden and self.errors:
  264. attrs["aria-invalid"] = "true"
  265. # Preserve aria-describedby provided by the attrs argument so user
  266. # can set the desired order.
  267. if not attrs.get("aria-describedby") and not self.use_fieldset:
  268. if aria_describedby := self.aria_describedby:
  269. attrs["aria-describedby"] = aria_describedby
  270. return attrs
  271. @property
  272. def aria_describedby(self):
  273. # Preserve aria-describedby set on the widget.
  274. if self.field.widget.attrs.get("aria-describedby"):
  275. return None
  276. aria_describedby = []
  277. if self.auto_id and not self.is_hidden:
  278. if self.help_text:
  279. aria_describedby.append(f"{self.auto_id}_helptext")
  280. if self.errors:
  281. aria_describedby.append(f"{self.auto_id}_error")
  282. return " ".join(aria_describedby)
  283. @property
  284. def widget_type(self):
  285. return re.sub(
  286. r"widget$|input$", "", self.field.widget.__class__.__name__.lower()
  287. )
  288. @property
  289. def use_fieldset(self):
  290. """
  291. Return the value of this BoundField widget's use_fieldset attribute.
  292. """
  293. return self.field.widget.use_fieldset
  294. @html_safe
  295. class BoundWidget:
  296. """
  297. A container class used for iterating over widgets. This is useful for
  298. widgets that have choices. For example, the following can be used in a
  299. template:
  300. {% for radio in myform.beatles %}
  301. <label for="{{ radio.id_for_label }}">
  302. {{ radio.choice_label }}
  303. <span class="radio">{{ radio.tag }}</span>
  304. </label>
  305. {% endfor %}
  306. """
  307. def __init__(self, parent_widget, data, renderer):
  308. self.parent_widget = parent_widget
  309. self.data = data
  310. self.renderer = renderer
  311. def __str__(self):
  312. return self.tag(wrap_label=True)
  313. def tag(self, wrap_label=False):
  314. context = {"widget": {**self.data, "wrap_label": wrap_label}}
  315. return self.parent_widget._render(self.template_name, context, self.renderer)
  316. @property
  317. def template_name(self):
  318. if "template_name" in self.data:
  319. return self.data["template_name"]
  320. return self.parent_widget.template_name
  321. @property
  322. def id_for_label(self):
  323. return self.data["attrs"].get("id")
  324. @property
  325. def choice_label(self):
  326. return self.data["label"]