You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

boundfield.py 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. 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(self.name, self.form.error_class())
  63. def as_widget(self, widget=None, attrs=None, only_initial=False):
  64. """
  65. Render the field by rendering the passed widget, adding any HTML
  66. attributes passed as attrs. If a widget isn't specified, use the
  67. field's default widget.
  68. """
  69. widget = widget or self.field.widget
  70. if self.field.localize:
  71. widget.is_localized = True
  72. attrs = attrs or {}
  73. attrs = self.build_widget_attrs(attrs, widget)
  74. if self.auto_id and 'id' not in widget.attrs:
  75. attrs.setdefault('id', self.html_initial_id if only_initial else self.auto_id)
  76. return widget.render(
  77. name=self.html_initial_name if only_initial else self.html_name,
  78. value=self.value(),
  79. attrs=attrs,
  80. renderer=self.form.renderer,
  81. )
  82. def as_text(self, attrs=None, **kwargs):
  83. """
  84. Return a string of HTML for representing this as an <input type="text">.
  85. """
  86. return self.as_widget(TextInput(), attrs, **kwargs)
  87. def as_textarea(self, attrs=None, **kwargs):
  88. """Return a string of HTML for representing this as a <textarea>."""
  89. return self.as_widget(Textarea(), attrs, **kwargs)
  90. def as_hidden(self, attrs=None, **kwargs):
  91. """
  92. Return a string of HTML for representing this as an <input type="hidden">.
  93. """
  94. return self.as_widget(self.field.hidden_widget(), attrs, **kwargs)
  95. @property
  96. def data(self):
  97. """
  98. Return the data for this BoundField, or None if it wasn't given.
  99. """
  100. return self.field.widget.value_from_datadict(self.form.data, self.form.files, self.html_name)
  101. def value(self):
  102. """
  103. Return the value for this BoundField, using the initial value if
  104. the form is not bound or the data otherwise.
  105. """
  106. data = self.initial
  107. if self.form.is_bound:
  108. data = self.field.bound_data(self.data, data)
  109. return self.field.prepare_value(data)
  110. def label_tag(self, contents=None, attrs=None, label_suffix=None):
  111. """
  112. Wrap the given contents in a <label>, if the field has an ID attribute.
  113. contents should be mark_safe'd to avoid HTML escaping. If contents
  114. aren't given, use the field's HTML-escaped label.
  115. If attrs are given, use them as HTML attributes on the <label> tag.
  116. label_suffix overrides the form's label_suffix.
  117. """
  118. contents = contents or self.label
  119. if label_suffix is None:
  120. label_suffix = (self.field.label_suffix if self.field.label_suffix is not None
  121. else self.form.label_suffix)
  122. # Only add the suffix if the label does not end in punctuation.
  123. # Translators: If found as last label character, these punctuation
  124. # characters will prevent the default label_suffix to be appended to the label
  125. if label_suffix and contents and contents[-1] not in _(':?.!'):
  126. contents = format_html('{}{}', contents, label_suffix)
  127. widget = self.field.widget
  128. id_ = widget.attrs.get('id') or self.auto_id
  129. if id_:
  130. id_for_label = widget.id_for_label(id_)
  131. if id_for_label:
  132. attrs = {**(attrs or {}), 'for': id_for_label}
  133. if self.field.required and hasattr(self.form, 'required_css_class'):
  134. attrs = attrs or {}
  135. if 'class' in attrs:
  136. attrs['class'] += ' ' + self.form.required_css_class
  137. else:
  138. attrs['class'] = self.form.required_css_class
  139. attrs = flatatt(attrs) if attrs else ''
  140. contents = format_html('<label{}>{}</label>', attrs, contents)
  141. else:
  142. contents = conditional_escape(contents)
  143. return mark_safe(contents)
  144. def css_classes(self, extra_classes=None):
  145. """
  146. Return a string of space-separated CSS classes for this field.
  147. """
  148. if hasattr(extra_classes, 'split'):
  149. extra_classes = extra_classes.split()
  150. extra_classes = set(extra_classes or [])
  151. if self.errors and hasattr(self.form, 'error_css_class'):
  152. extra_classes.add(self.form.error_css_class)
  153. if self.field.required and hasattr(self.form, 'required_css_class'):
  154. extra_classes.add(self.form.required_css_class)
  155. return ' '.join(extra_classes)
  156. @property
  157. def is_hidden(self):
  158. """Return True if this BoundField's widget is hidden."""
  159. return self.field.widget.is_hidden
  160. @property
  161. def auto_id(self):
  162. """
  163. Calculate and return the ID attribute for this BoundField, if the
  164. associated Form has specified auto_id. Return an empty string otherwise.
  165. """
  166. auto_id = self.form.auto_id # Boolean or string
  167. if auto_id and '%s' in str(auto_id):
  168. return auto_id % self.html_name
  169. elif auto_id:
  170. return self.html_name
  171. return ''
  172. @property
  173. def id_for_label(self):
  174. """
  175. Wrapper around the field widget's `id_for_label` method.
  176. Useful, for example, for focusing on this field regardless of whether
  177. it has a single widget or a MultiWidget.
  178. """
  179. widget = self.field.widget
  180. id_ = widget.attrs.get('id') or self.auto_id
  181. return widget.id_for_label(id_)
  182. @cached_property
  183. def initial(self):
  184. data = self.form.get_initial_for_field(self.field, self.name)
  185. # If this is an auto-generated default date, nix the microseconds for
  186. # standardized handling. See #22502.
  187. if (isinstance(data, (datetime.datetime, datetime.time)) and
  188. not self.field.widget.supports_microseconds):
  189. data = data.replace(microsecond=0)
  190. return data
  191. def build_widget_attrs(self, attrs, widget=None):
  192. widget = widget or self.field.widget
  193. attrs = dict(attrs) # Copy attrs to avoid modifying the argument.
  194. if widget.use_required_attribute(self.initial) and self.field.required and self.form.use_required_attribute:
  195. attrs['required'] = True
  196. if self.field.disabled:
  197. attrs['disabled'] = True
  198. return attrs
  199. @html_safe
  200. class BoundWidget:
  201. """
  202. A container class used for iterating over widgets. This is useful for
  203. widgets that have choices. For example, the following can be used in a
  204. template:
  205. {% for radio in myform.beatles %}
  206. <label for="{{ radio.id_for_label }}">
  207. {{ radio.choice_label }}
  208. <span class="radio">{{ radio.tag }}</span>
  209. </label>
  210. {% endfor %}
  211. """
  212. def __init__(self, parent_widget, data, renderer):
  213. self.parent_widget = parent_widget
  214. self.data = data
  215. self.renderer = renderer
  216. def __str__(self):
  217. return self.tag(wrap_label=True)
  218. def tag(self, wrap_label=False):
  219. context = {'widget': {**self.data, 'wrap_label': wrap_label}}
  220. return self.parent_widget._render(self.template_name, context, self.renderer)
  221. @property
  222. def template_name(self):
  223. if 'template_name' in self.data:
  224. return self.data['template_name']
  225. return self.parent_widget.template_name
  226. @property
  227. def id_for_label(self):
  228. return 'id_%s_%s' % (self.data['name'], self.data['index'])
  229. @property
  230. def choice_label(self):
  231. return self.data['label']