boundfield.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import re
  2. from django.core.exceptions import ValidationError
  3. from django.forms.utils import 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. @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(
  43. self.html_name, self.value(), attrs=attrs
  44. )
  45. ]
  46. def __bool__(self):
  47. # BoundField evaluates to True even if it doesn't have subwidgets.
  48. return True
  49. def __iter__(self):
  50. return iter(self.subwidgets)
  51. def __len__(self):
  52. return len(self.subwidgets)
  53. def __getitem__(self, idx):
  54. # Prevent unnecessary reevaluation when accessing BoundField's attrs
  55. # from templates.
  56. if not isinstance(idx, (int, slice)):
  57. raise TypeError(
  58. "BoundField indices must be integers or slices, not %s."
  59. % type(idx).__name__
  60. )
  61. return self.subwidgets[idx]
  62. @property
  63. def errors(self):
  64. """
  65. Return an ErrorList (empty if there are no errors) for this field.
  66. """
  67. return self.form.errors.get(
  68. self.name, self.form.error_class(renderer=self.form.renderer)
  69. )
  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. return attrs
  258. @property
  259. def widget_type(self):
  260. return re.sub(
  261. r"widget$|input$", "", self.field.widget.__class__.__name__.lower()
  262. )
  263. @property
  264. def use_fieldset(self):
  265. """
  266. Return the value of this BoundField widget's use_fieldset attribute.
  267. """
  268. return self.field.widget.use_fieldset
  269. @html_safe
  270. class BoundWidget:
  271. """
  272. A container class used for iterating over widgets. This is useful for
  273. widgets that have choices. For example, the following can be used in a
  274. template:
  275. {% for radio in myform.beatles %}
  276. <label for="{{ radio.id_for_label }}">
  277. {{ radio.choice_label }}
  278. <span class="radio">{{ radio.tag }}</span>
  279. </label>
  280. {% endfor %}
  281. """
  282. def __init__(self, parent_widget, data, renderer):
  283. self.parent_widget = parent_widget
  284. self.data = data
  285. self.renderer = renderer
  286. def __str__(self):
  287. return self.tag(wrap_label=True)
  288. def tag(self, wrap_label=False):
  289. context = {"widget": {**self.data, "wrap_label": wrap_label}}
  290. return self.parent_widget._render(self.template_name, context, self.renderer)
  291. @property
  292. def template_name(self):
  293. if "template_name" in self.data:
  294. return self.data["template_name"]
  295. return self.parent_widget.template_name
  296. @property
  297. def id_for_label(self):
  298. return self.data["attrs"].get("id")
  299. @property
  300. def choice_label(self):
  301. return self.data["label"]