Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 12KB

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