boundfield.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 <input type="text">.
  102. """
  103. return self.as_widget(TextInput(), attrs, **kwargs)
  104. def as_textarea(self, attrs=None, **kwargs):
  105. """Return a string of HTML for representing this as a <textarea>."""
  106. return self.as_widget(Textarea(), attrs, **kwargs)
  107. def as_hidden(self, attrs=None, **kwargs):
  108. """
  109. Return a string of HTML for representing this as an <input type="hidden">.
  110. """
  111. return self.as_widget(self.field.hidden_widget(), attrs, **kwargs)
  112. @property
  113. def data(self):
  114. """
  115. Return the data for this BoundField, or None if it wasn't given.
  116. """
  117. return self.form._widget_data_value(self.field.widget, self.html_name)
  118. def value(self):
  119. """
  120. Return the value for this BoundField, using the initial value if
  121. the form is not bound or the data otherwise.
  122. """
  123. data = self.initial
  124. if self.form.is_bound:
  125. data = self.field.bound_data(self.data, data)
  126. return self.field.prepare_value(data)
  127. def _has_changed(self):
  128. field = self.field
  129. if field.show_hidden_initial:
  130. hidden_widget = field.hidden_widget()
  131. initial_value = self.form._widget_data_value(
  132. hidden_widget,
  133. self.html_initial_name,
  134. )
  135. try:
  136. initial_value = field.to_python(initial_value)
  137. except ValidationError:
  138. # Always assume data has changed if validation fails.
  139. return True
  140. else:
  141. initial_value = self.initial
  142. return field.has_changed(initial_value, self.data)
  143. def label_tag(self, contents=None, attrs=None, label_suffix=None, tag=None):
  144. """
  145. Wrap the given contents in a <label>, if the field has an ID attribute.
  146. contents should be mark_safe'd to avoid HTML escaping. If contents
  147. aren't given, use the field's HTML-escaped label.
  148. If attrs are given, use them as HTML attributes on the <label> tag.
  149. label_suffix overrides the form's label_suffix.
  150. """
  151. contents = contents or self.label
  152. if label_suffix is None:
  153. label_suffix = (
  154. self.field.label_suffix
  155. if self.field.label_suffix is not None
  156. else self.form.label_suffix
  157. )
  158. # Only add the suffix if the label does not end in punctuation.
  159. # Translators: If found as last label character, these punctuation
  160. # characters will prevent the default label_suffix to be appended to the label
  161. if label_suffix and contents and contents[-1] not in _(":?.!"):
  162. contents = format_html("{}{}", contents, label_suffix)
  163. widget = self.field.widget
  164. id_ = widget.attrs.get("id") or self.auto_id
  165. if id_:
  166. id_for_label = widget.id_for_label(id_)
  167. if id_for_label:
  168. attrs = {**(attrs or {}), "for": id_for_label}
  169. if self.field.required and hasattr(self.form, "required_css_class"):
  170. attrs = attrs or {}
  171. if "class" in attrs:
  172. attrs["class"] += " " + self.form.required_css_class
  173. else:
  174. attrs["class"] = self.form.required_css_class
  175. context = {
  176. "field": self,
  177. "label": contents,
  178. "attrs": attrs,
  179. "use_tag": bool(id_),
  180. "tag": tag or "label",
  181. }
  182. return self.form.render(self.form.template_name_label, context)
  183. def legend_tag(self, contents=None, attrs=None, label_suffix=None):
  184. """
  185. Wrap the given contents in a <legend>, if the field has an ID
  186. attribute. Contents should be mark_safe'd to avoid HTML escaping. If
  187. contents aren't given, use the field's HTML-escaped label.
  188. If attrs are given, use them as HTML attributes on the <legend> tag.
  189. label_suffix overrides the form's label_suffix.
  190. """
  191. return self.label_tag(contents, attrs, label_suffix, tag="legend")
  192. def css_classes(self, extra_classes=None):
  193. """
  194. Return a string of space-separated CSS classes for this field.
  195. """
  196. if hasattr(extra_classes, "split"):
  197. extra_classes = extra_classes.split()
  198. extra_classes = set(extra_classes or [])
  199. if self.errors and hasattr(self.form, "error_css_class"):
  200. extra_classes.add(self.form.error_css_class)
  201. if self.field.required and hasattr(self.form, "required_css_class"):
  202. extra_classes.add(self.form.required_css_class)
  203. return " ".join(extra_classes)
  204. @property
  205. def is_hidden(self):
  206. """Return True if this BoundField's widget is hidden."""
  207. return self.field.widget.is_hidden
  208. @property
  209. def auto_id(self):
  210. """
  211. Calculate and return the ID attribute for this BoundField, if the
  212. associated Form has specified auto_id. Return an empty string otherwise.
  213. """
  214. auto_id = self.form.auto_id # Boolean or string
  215. if auto_id and "%s" in str(auto_id):
  216. return auto_id % self.html_name
  217. elif auto_id:
  218. return self.html_name
  219. return ""
  220. @property
  221. def id_for_label(self):
  222. """
  223. Wrapper around the field widget's `id_for_label` method.
  224. Useful, for example, for focusing on this field regardless of whether
  225. it has a single widget or a MultiWidget.
  226. """
  227. widget = self.field.widget
  228. id_ = widget.attrs.get("id") or self.auto_id
  229. return widget.id_for_label(id_)
  230. @cached_property
  231. def initial(self):
  232. return self.form.get_initial_for_field(self.field, self.name)
  233. def build_widget_attrs(self, attrs, widget=None):
  234. widget = widget or self.field.widget
  235. attrs = dict(attrs) # Copy attrs to avoid modifying the argument.
  236. if (
  237. widget.use_required_attribute(self.initial)
  238. and self.field.required
  239. and self.form.use_required_attribute
  240. ):
  241. # MultiValueField has require_all_fields: if False, fall back
  242. # on subfields.
  243. if (
  244. hasattr(self.field, "require_all_fields")
  245. and not self.field.require_all_fields
  246. and isinstance(self.field.widget, MultiWidget)
  247. ):
  248. for subfield, subwidget in zip(self.field.fields, widget.widgets):
  249. subwidget.attrs["required"] = (
  250. subwidget.use_required_attribute(self.initial)
  251. and subfield.required
  252. )
  253. else:
  254. attrs["required"] = True
  255. if self.field.disabled:
  256. attrs["disabled"] = True
  257. if not widget.is_hidden and self.errors:
  258. attrs["aria-invalid"] = "true"
  259. # If a custom aria-describedby attribute is given (either via the attrs
  260. # argument or widget.attrs) and help_text is used, the custom
  261. # aria-described by is preserved so user can set the desired order.
  262. if (
  263. not attrs.get("aria-describedby")
  264. and not widget.attrs.get("aria-describedby")
  265. and self.field.help_text
  266. and not self.use_fieldset
  267. and self.auto_id
  268. ):
  269. attrs["aria-describedby"] = f"{self.auto_id}_helptext"
  270. return attrs
  271. @property
  272. def widget_type(self):
  273. return re.sub(
  274. r"widget$|input$", "", self.field.widget.__class__.__name__.lower()
  275. )
  276. @property
  277. def use_fieldset(self):
  278. """
  279. Return the value of this BoundField widget's use_fieldset attribute.
  280. """
  281. return self.field.widget.use_fieldset
  282. @html_safe
  283. class BoundWidget:
  284. """
  285. A container class used for iterating over widgets. This is useful for
  286. widgets that have choices. For example, the following can be used in a
  287. template:
  288. {% for radio in myform.beatles %}
  289. <label for="{{ radio.id_for_label }}">
  290. {{ radio.choice_label }}
  291. <span class="radio">{{ radio.tag }}</span>
  292. </label>
  293. {% endfor %}
  294. """
  295. def __init__(self, parent_widget, data, renderer):
  296. self.parent_widget = parent_widget
  297. self.data = data
  298. self.renderer = renderer
  299. def __str__(self):
  300. return self.tag(wrap_label=True)
  301. def tag(self, wrap_label=False):
  302. context = {"widget": {**self.data, "wrap_label": wrap_label}}
  303. return self.parent_widget._render(self.template_name, context, self.renderer)
  304. @property
  305. def template_name(self):
  306. if "template_name" in self.data:
  307. return self.data["template_name"]
  308. return self.parent_widget.template_name
  309. @property
  310. def id_for_label(self):
  311. return self.data["attrs"].get("id")
  312. @property
  313. def choice_label(self):
  314. return self.data["label"]