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.

widgets.py 38KB

1 year ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. """
  2. HTML Widget classes
  3. """
  4. import copy
  5. import datetime
  6. import warnings
  7. from collections import defaultdict
  8. from itertools import chain
  9. from django.forms.utils import to_current_timezone
  10. from django.templatetags.static import static
  11. from django.utils import formats
  12. from django.utils.datastructures import OrderedSet
  13. from django.utils.dates import MONTHS
  14. from django.utils.formats import get_format
  15. from django.utils.html import format_html, html_safe
  16. from django.utils.regex_helper import _lazy_re_compile
  17. from django.utils.safestring import mark_safe
  18. from django.utils.topological_sort import CyclicDependencyError, stable_topological_sort
  19. from django.utils.translation import gettext_lazy as _
  20. from .renderers import get_default_renderer
  21. __all__ = (
  22. "Media",
  23. "MediaDefiningClass",
  24. "Widget",
  25. "TextInput",
  26. "NumberInput",
  27. "EmailInput",
  28. "URLInput",
  29. "PasswordInput",
  30. "HiddenInput",
  31. "MultipleHiddenInput",
  32. "FileInput",
  33. "ClearableFileInput",
  34. "Textarea",
  35. "DateInput",
  36. "DateTimeInput",
  37. "TimeInput",
  38. "CheckboxInput",
  39. "Select",
  40. "NullBooleanSelect",
  41. "SelectMultiple",
  42. "RadioSelect",
  43. "CheckboxSelectMultiple",
  44. "MultiWidget",
  45. "SplitDateTimeWidget",
  46. "SplitHiddenDateTimeWidget",
  47. "SelectDateWidget",
  48. )
  49. MEDIA_TYPES = ("css", "js")
  50. class MediaOrderConflictWarning(RuntimeWarning):
  51. pass
  52. @html_safe
  53. class Media:
  54. def __init__(self, media=None, css=None, js=None):
  55. if media is not None:
  56. css = getattr(media, "css", {})
  57. js = getattr(media, "js", [])
  58. else:
  59. if css is None:
  60. css = {}
  61. if js is None:
  62. js = []
  63. self._css_lists = [css]
  64. self._js_lists = [js]
  65. def __repr__(self):
  66. return "Media(css=%r, js=%r)" % (self._css, self._js)
  67. def __str__(self):
  68. return self.render()
  69. @property
  70. def _css(self):
  71. css = defaultdict(list)
  72. for css_list in self._css_lists:
  73. for medium, sublist in css_list.items():
  74. css[medium].append(sublist)
  75. return {medium: self.merge(*lists) for medium, lists in css.items()}
  76. @property
  77. def _js(self):
  78. return self.merge(*self._js_lists)
  79. def render(self):
  80. return mark_safe(
  81. "\n".join(
  82. chain.from_iterable(
  83. getattr(self, "render_" + name)() for name in MEDIA_TYPES
  84. )
  85. )
  86. )
  87. def render_js(self):
  88. return [
  89. path.__html__()
  90. if hasattr(path, "__html__")
  91. else format_html('<script src="{}"></script>', self.absolute_path(path))
  92. for path in self._js
  93. ]
  94. def render_css(self):
  95. # To keep rendering order consistent, we can't just iterate over items().
  96. # We need to sort the keys, and iterate over the sorted list.
  97. media = sorted(self._css)
  98. return chain.from_iterable(
  99. [
  100. path.__html__()
  101. if hasattr(path, "__html__")
  102. else format_html(
  103. '<link href="{}" media="{}" rel="stylesheet">',
  104. self.absolute_path(path),
  105. medium,
  106. )
  107. for path in self._css[medium]
  108. ]
  109. for medium in media
  110. )
  111. def absolute_path(self, path):
  112. """
  113. Given a relative or absolute path to a static asset, return an absolute
  114. path. An absolute path will be returned unchanged while a relative path
  115. will be passed to django.templatetags.static.static().
  116. """
  117. if path.startswith(("http://", "https://", "/")):
  118. return path
  119. return static(path)
  120. def __getitem__(self, name):
  121. """Return a Media object that only contains media of the given type."""
  122. if name in MEDIA_TYPES:
  123. return Media(**{str(name): getattr(self, "_" + name)})
  124. raise KeyError('Unknown media type "%s"' % name)
  125. @staticmethod
  126. def merge(*lists):
  127. """
  128. Merge lists while trying to keep the relative order of the elements.
  129. Warn if the lists have the same elements in a different relative order.
  130. For static assets it can be important to have them included in the DOM
  131. in a certain order. In JavaScript you may not be able to reference a
  132. global or in CSS you might want to override a style.
  133. """
  134. dependency_graph = defaultdict(set)
  135. all_items = OrderedSet()
  136. for list_ in filter(None, lists):
  137. head = list_[0]
  138. # The first items depend on nothing but have to be part of the
  139. # dependency graph to be included in the result.
  140. dependency_graph.setdefault(head, set())
  141. for item in list_:
  142. all_items.add(item)
  143. # No self dependencies
  144. if head != item:
  145. dependency_graph[item].add(head)
  146. head = item
  147. try:
  148. return stable_topological_sort(all_items, dependency_graph)
  149. except CyclicDependencyError:
  150. warnings.warn(
  151. "Detected duplicate Media files in an opposite order: {}".format(
  152. ", ".join(repr(list_) for list_ in lists)
  153. ),
  154. MediaOrderConflictWarning,
  155. )
  156. return list(all_items)
  157. def __add__(self, other):
  158. combined = Media()
  159. combined._css_lists = self._css_lists[:]
  160. combined._js_lists = self._js_lists[:]
  161. for item in other._css_lists:
  162. if item and item not in self._css_lists:
  163. combined._css_lists.append(item)
  164. for item in other._js_lists:
  165. if item and item not in self._js_lists:
  166. combined._js_lists.append(item)
  167. return combined
  168. def media_property(cls):
  169. def _media(self):
  170. # Get the media property of the superclass, if it exists
  171. sup_cls = super(cls, self)
  172. try:
  173. base = sup_cls.media
  174. except AttributeError:
  175. base = Media()
  176. # Get the media definition for this class
  177. definition = getattr(cls, "Media", None)
  178. if definition:
  179. extend = getattr(definition, "extend", True)
  180. if extend:
  181. if extend is True:
  182. m = base
  183. else:
  184. m = Media()
  185. for medium in extend:
  186. m = m + base[medium]
  187. return m + Media(definition)
  188. return Media(definition)
  189. return base
  190. return property(_media)
  191. class MediaDefiningClass(type):
  192. """
  193. Metaclass for classes that can have media definitions.
  194. """
  195. def __new__(mcs, name, bases, attrs):
  196. new_class = super().__new__(mcs, name, bases, attrs)
  197. if "media" not in attrs:
  198. new_class.media = media_property(new_class)
  199. return new_class
  200. class Widget(metaclass=MediaDefiningClass):
  201. needs_multipart_form = False # Determines does this widget need multipart form
  202. is_localized = False
  203. is_required = False
  204. supports_microseconds = True
  205. use_fieldset = False
  206. def __init__(self, attrs=None):
  207. self.attrs = {} if attrs is None else attrs.copy()
  208. def __deepcopy__(self, memo):
  209. obj = copy.copy(self)
  210. obj.attrs = self.attrs.copy()
  211. memo[id(self)] = obj
  212. return obj
  213. @property
  214. def is_hidden(self):
  215. return self.input_type == "hidden" if hasattr(self, "input_type") else False
  216. def subwidgets(self, name, value, attrs=None):
  217. context = self.get_context(name, value, attrs)
  218. yield context["widget"]
  219. def format_value(self, value):
  220. """
  221. Return a value as it should appear when rendered in a template.
  222. """
  223. if value == "" or value is None:
  224. return None
  225. if self.is_localized:
  226. return formats.localize_input(value)
  227. return str(value)
  228. def get_context(self, name, value, attrs):
  229. return {
  230. "widget": {
  231. "name": name,
  232. "is_hidden": self.is_hidden,
  233. "required": self.is_required,
  234. "value": self.format_value(value),
  235. "attrs": self.build_attrs(self.attrs, attrs),
  236. "template_name": self.template_name,
  237. },
  238. }
  239. def render(self, name, value, attrs=None, renderer=None):
  240. """Render the widget as an HTML string."""
  241. context = self.get_context(name, value, attrs)
  242. return self._render(self.template_name, context, renderer)
  243. def _render(self, template_name, context, renderer=None):
  244. if renderer is None:
  245. renderer = get_default_renderer()
  246. return mark_safe(renderer.render(template_name, context))
  247. def build_attrs(self, base_attrs, extra_attrs=None):
  248. """Build an attribute dictionary."""
  249. return {**base_attrs, **(extra_attrs or {})}
  250. def value_from_datadict(self, data, files, name):
  251. """
  252. Given a dictionary of data and this widget's name, return the value
  253. of this widget or None if it's not provided.
  254. """
  255. return data.get(name)
  256. def value_omitted_from_data(self, data, files, name):
  257. return name not in data
  258. def id_for_label(self, id_):
  259. """
  260. Return the HTML ID attribute of this Widget for use by a <label>, given
  261. the ID of the field. Return an empty string if no ID is available.
  262. This hook is necessary because some widgets have multiple HTML
  263. elements and, thus, multiple IDs. In that case, this method should
  264. return an ID value that corresponds to the first ID in the widget's
  265. tags.
  266. """
  267. return id_
  268. def use_required_attribute(self, initial):
  269. return not self.is_hidden
  270. class Input(Widget):
  271. """
  272. Base class for all <input> widgets.
  273. """
  274. input_type = None # Subclasses must define this.
  275. template_name = "django/forms/widgets/input.html"
  276. def __init__(self, attrs=None):
  277. if attrs is not None:
  278. attrs = attrs.copy()
  279. self.input_type = attrs.pop("type", self.input_type)
  280. super().__init__(attrs)
  281. def get_context(self, name, value, attrs):
  282. context = super().get_context(name, value, attrs)
  283. context["widget"]["type"] = self.input_type
  284. return context
  285. class TextInput(Input):
  286. input_type = "text"
  287. template_name = "django/forms/widgets/text.html"
  288. class NumberInput(Input):
  289. input_type = "number"
  290. template_name = "django/forms/widgets/number.html"
  291. class EmailInput(Input):
  292. input_type = "email"
  293. template_name = "django/forms/widgets/email.html"
  294. class URLInput(Input):
  295. input_type = "url"
  296. template_name = "django/forms/widgets/url.html"
  297. class PasswordInput(Input):
  298. input_type = "password"
  299. template_name = "django/forms/widgets/password.html"
  300. def __init__(self, attrs=None, render_value=False):
  301. super().__init__(attrs)
  302. self.render_value = render_value
  303. def get_context(self, name, value, attrs):
  304. if not self.render_value:
  305. value = None
  306. return super().get_context(name, value, attrs)
  307. class HiddenInput(Input):
  308. input_type = "hidden"
  309. template_name = "django/forms/widgets/hidden.html"
  310. class MultipleHiddenInput(HiddenInput):
  311. """
  312. Handle <input type="hidden"> for fields that have a list
  313. of values.
  314. """
  315. template_name = "django/forms/widgets/multiple_hidden.html"
  316. def get_context(self, name, value, attrs):
  317. context = super().get_context(name, value, attrs)
  318. final_attrs = context["widget"]["attrs"]
  319. id_ = context["widget"]["attrs"].get("id")
  320. subwidgets = []
  321. for index, value_ in enumerate(context["widget"]["value"]):
  322. widget_attrs = final_attrs.copy()
  323. if id_:
  324. # An ID attribute was given. Add a numeric index as a suffix
  325. # so that the inputs don't all have the same ID attribute.
  326. widget_attrs["id"] = "%s_%s" % (id_, index)
  327. widget = HiddenInput()
  328. widget.is_required = self.is_required
  329. subwidgets.append(widget.get_context(name, value_, widget_attrs)["widget"])
  330. context["widget"]["subwidgets"] = subwidgets
  331. return context
  332. def value_from_datadict(self, data, files, name):
  333. try:
  334. getter = data.getlist
  335. except AttributeError:
  336. getter = data.get
  337. return getter(name)
  338. def format_value(self, value):
  339. return [] if value is None else value
  340. class FileInput(Input):
  341. input_type = "file"
  342. needs_multipart_form = True
  343. template_name = "django/forms/widgets/file.html"
  344. def format_value(self, value):
  345. """File input never renders a value."""
  346. return
  347. def value_from_datadict(self, data, files, name):
  348. "File widgets take data from FILES, not POST"
  349. return files.get(name)
  350. def value_omitted_from_data(self, data, files, name):
  351. return name not in files
  352. def use_required_attribute(self, initial):
  353. return super().use_required_attribute(initial) and not initial
  354. FILE_INPUT_CONTRADICTION = object()
  355. class ClearableFileInput(FileInput):
  356. clear_checkbox_label = _("Clear")
  357. initial_text = _("Currently")
  358. input_text = _("Change")
  359. template_name = "django/forms/widgets/clearable_file_input.html"
  360. def clear_checkbox_name(self, name):
  361. """
  362. Given the name of the file input, return the name of the clear checkbox
  363. input.
  364. """
  365. return name + "-clear"
  366. def clear_checkbox_id(self, name):
  367. """
  368. Given the name of the clear checkbox input, return the HTML id for it.
  369. """
  370. return name + "_id"
  371. def is_initial(self, value):
  372. """
  373. Return whether value is considered to be initial value.
  374. """
  375. return bool(value and getattr(value, "url", False))
  376. def format_value(self, value):
  377. """
  378. Return the file object if it has a defined url attribute.
  379. """
  380. if self.is_initial(value):
  381. return value
  382. def get_context(self, name, value, attrs):
  383. context = super().get_context(name, value, attrs)
  384. checkbox_name = self.clear_checkbox_name(name)
  385. checkbox_id = self.clear_checkbox_id(checkbox_name)
  386. context["widget"].update(
  387. {
  388. "checkbox_name": checkbox_name,
  389. "checkbox_id": checkbox_id,
  390. "is_initial": self.is_initial(value),
  391. "input_text": self.input_text,
  392. "initial_text": self.initial_text,
  393. "clear_checkbox_label": self.clear_checkbox_label,
  394. }
  395. )
  396. return context
  397. def value_from_datadict(self, data, files, name):
  398. upload = super().value_from_datadict(data, files, name)
  399. if not self.is_required and CheckboxInput().value_from_datadict(
  400. data, files, self.clear_checkbox_name(name)
  401. ):
  402. if upload:
  403. # If the user contradicts themselves (uploads a new file AND
  404. # checks the "clear" checkbox), we return a unique marker
  405. # object that FileField will turn into a ValidationError.
  406. return FILE_INPUT_CONTRADICTION
  407. # False signals to clear any existing value, as opposed to just None
  408. return False
  409. return upload
  410. def value_omitted_from_data(self, data, files, name):
  411. return (
  412. super().value_omitted_from_data(data, files, name)
  413. and self.clear_checkbox_name(name) not in data
  414. )
  415. class Textarea(Widget):
  416. template_name = "django/forms/widgets/textarea.html"
  417. def __init__(self, attrs=None):
  418. # Use slightly better defaults than HTML's 20x2 box
  419. default_attrs = {"cols": "40", "rows": "10"}
  420. if attrs:
  421. default_attrs.update(attrs)
  422. super().__init__(default_attrs)
  423. class DateTimeBaseInput(TextInput):
  424. format_key = ""
  425. supports_microseconds = False
  426. def __init__(self, attrs=None, format=None):
  427. super().__init__(attrs)
  428. self.format = format or None
  429. def format_value(self, value):
  430. return formats.localize_input(
  431. value, self.format or formats.get_format(self.format_key)[0]
  432. )
  433. class DateInput(DateTimeBaseInput):
  434. format_key = "DATE_INPUT_FORMATS"
  435. template_name = "django/forms/widgets/date.html"
  436. class DateTimeInput(DateTimeBaseInput):
  437. format_key = "DATETIME_INPUT_FORMATS"
  438. template_name = "django/forms/widgets/datetime.html"
  439. class TimeInput(DateTimeBaseInput):
  440. format_key = "TIME_INPUT_FORMATS"
  441. template_name = "django/forms/widgets/time.html"
  442. # Defined at module level so that CheckboxInput is picklable (#17976)
  443. def boolean_check(v):
  444. return not (v is False or v is None or v == "")
  445. class CheckboxInput(Input):
  446. input_type = "checkbox"
  447. template_name = "django/forms/widgets/checkbox.html"
  448. def __init__(self, attrs=None, check_test=None):
  449. super().__init__(attrs)
  450. # check_test is a callable that takes a value and returns True
  451. # if the checkbox should be checked for that value.
  452. self.check_test = boolean_check if check_test is None else check_test
  453. def format_value(self, value):
  454. """Only return the 'value' attribute if value isn't empty."""
  455. if value is True or value is False or value is None or value == "":
  456. return
  457. return str(value)
  458. def get_context(self, name, value, attrs):
  459. if self.check_test(value):
  460. attrs = {**(attrs or {}), "checked": True}
  461. return super().get_context(name, value, attrs)
  462. def value_from_datadict(self, data, files, name):
  463. if name not in data:
  464. # A missing value means False because HTML form submission does not
  465. # send results for unselected checkboxes.
  466. return False
  467. value = data.get(name)
  468. # Translate true and false strings to boolean values.
  469. values = {"true": True, "false": False}
  470. if isinstance(value, str):
  471. value = values.get(value.lower(), value)
  472. return bool(value)
  473. def value_omitted_from_data(self, data, files, name):
  474. # HTML checkboxes don't appear in POST data if not checked, so it's
  475. # never known if the value is actually omitted.
  476. return False
  477. class ChoiceWidget(Widget):
  478. allow_multiple_selected = False
  479. input_type = None
  480. template_name = None
  481. option_template_name = None
  482. add_id_index = True
  483. checked_attribute = {"checked": True}
  484. option_inherits_attrs = True
  485. def __init__(self, attrs=None, choices=()):
  486. super().__init__(attrs)
  487. # choices can be any iterable, but we may need to render this widget
  488. # multiple times. Thus, collapse it into a list so it can be consumed
  489. # more than once.
  490. self.choices = list(choices)
  491. def __deepcopy__(self, memo):
  492. obj = copy.copy(self)
  493. obj.attrs = self.attrs.copy()
  494. obj.choices = copy.copy(self.choices)
  495. memo[id(self)] = obj
  496. return obj
  497. def subwidgets(self, name, value, attrs=None):
  498. """
  499. Yield all "subwidgets" of this widget. Used to enable iterating
  500. options from a BoundField for choice widgets.
  501. """
  502. value = self.format_value(value)
  503. yield from self.options(name, value, attrs)
  504. def options(self, name, value, attrs=None):
  505. """Yield a flat list of options for this widget."""
  506. for group in self.optgroups(name, value, attrs):
  507. yield from group[1]
  508. def optgroups(self, name, value, attrs=None):
  509. """Return a list of optgroups for this widget."""
  510. groups = []
  511. has_selected = False
  512. for index, (option_value, option_label) in enumerate(self.choices):
  513. if option_value is None:
  514. option_value = ""
  515. subgroup = []
  516. if isinstance(option_label, (list, tuple)):
  517. group_name = option_value
  518. subindex = 0
  519. choices = option_label
  520. else:
  521. group_name = None
  522. subindex = None
  523. choices = [(option_value, option_label)]
  524. groups.append((group_name, subgroup, index))
  525. for subvalue, sublabel in choices:
  526. selected = (not has_selected or self.allow_multiple_selected) and str(
  527. subvalue
  528. ) in value
  529. has_selected |= selected
  530. subgroup.append(
  531. self.create_option(
  532. name,
  533. subvalue,
  534. sublabel,
  535. selected,
  536. index,
  537. subindex=subindex,
  538. attrs=attrs,
  539. )
  540. )
  541. if subindex is not None:
  542. subindex += 1
  543. return groups
  544. def create_option(
  545. self, name, value, label, selected, index, subindex=None, attrs=None
  546. ):
  547. index = str(index) if subindex is None else "%s_%s" % (index, subindex)
  548. option_attrs = (
  549. self.build_attrs(self.attrs, attrs) if self.option_inherits_attrs else {}
  550. )
  551. if selected:
  552. option_attrs.update(self.checked_attribute)
  553. if "id" in option_attrs:
  554. option_attrs["id"] = self.id_for_label(option_attrs["id"], index)
  555. return {
  556. "name": name,
  557. "value": value,
  558. "label": label,
  559. "selected": selected,
  560. "index": index,
  561. "attrs": option_attrs,
  562. "type": self.input_type,
  563. "template_name": self.option_template_name,
  564. "wrap_label": True,
  565. }
  566. def get_context(self, name, value, attrs):
  567. context = super().get_context(name, value, attrs)
  568. context["widget"]["optgroups"] = self.optgroups(
  569. name, context["widget"]["value"], attrs
  570. )
  571. return context
  572. def id_for_label(self, id_, index="0"):
  573. """
  574. Use an incremented id for each option where the main widget
  575. references the zero index.
  576. """
  577. if id_ and self.add_id_index:
  578. id_ = "%s_%s" % (id_, index)
  579. return id_
  580. def value_from_datadict(self, data, files, name):
  581. getter = data.get
  582. if self.allow_multiple_selected:
  583. try:
  584. getter = data.getlist
  585. except AttributeError:
  586. pass
  587. return getter(name)
  588. def format_value(self, value):
  589. """Return selected values as a list."""
  590. if value is None and self.allow_multiple_selected:
  591. return []
  592. if not isinstance(value, (tuple, list)):
  593. value = [value]
  594. return [str(v) if v is not None else "" for v in value]
  595. class Select(ChoiceWidget):
  596. input_type = "select"
  597. template_name = "django/forms/widgets/select.html"
  598. option_template_name = "django/forms/widgets/select_option.html"
  599. add_id_index = False
  600. checked_attribute = {"selected": True}
  601. option_inherits_attrs = False
  602. def get_context(self, name, value, attrs):
  603. context = super().get_context(name, value, attrs)
  604. if self.allow_multiple_selected:
  605. context["widget"]["attrs"]["multiple"] = True
  606. return context
  607. @staticmethod
  608. def _choice_has_empty_value(choice):
  609. """Return True if the choice's value is empty string or None."""
  610. value, _ = choice
  611. return value is None or value == ""
  612. def use_required_attribute(self, initial):
  613. """
  614. Don't render 'required' if the first <option> has a value, as that's
  615. invalid HTML.
  616. """
  617. use_required_attribute = super().use_required_attribute(initial)
  618. # 'required' is always okay for <select multiple>.
  619. if self.allow_multiple_selected:
  620. return use_required_attribute
  621. first_choice = next(iter(self.choices), None)
  622. return (
  623. use_required_attribute
  624. and first_choice is not None
  625. and self._choice_has_empty_value(first_choice)
  626. )
  627. class NullBooleanSelect(Select):
  628. """
  629. A Select Widget intended to be used with NullBooleanField.
  630. """
  631. def __init__(self, attrs=None):
  632. choices = (
  633. ("unknown", _("Unknown")),
  634. ("true", _("Yes")),
  635. ("false", _("No")),
  636. )
  637. super().__init__(attrs, choices)
  638. def format_value(self, value):
  639. try:
  640. return {
  641. True: "true",
  642. False: "false",
  643. "true": "true",
  644. "false": "false",
  645. # For backwards compatibility with Django < 2.2.
  646. "2": "true",
  647. "3": "false",
  648. }[value]
  649. except KeyError:
  650. return "unknown"
  651. def value_from_datadict(self, data, files, name):
  652. value = data.get(name)
  653. return {
  654. True: True,
  655. "True": True,
  656. "False": False,
  657. False: False,
  658. "true": True,
  659. "false": False,
  660. # For backwards compatibility with Django < 2.2.
  661. "2": True,
  662. "3": False,
  663. }.get(value)
  664. class SelectMultiple(Select):
  665. allow_multiple_selected = True
  666. def value_from_datadict(self, data, files, name):
  667. try:
  668. getter = data.getlist
  669. except AttributeError:
  670. getter = data.get
  671. return getter(name)
  672. def value_omitted_from_data(self, data, files, name):
  673. # An unselected <select multiple> doesn't appear in POST data, so it's
  674. # never known if the value is actually omitted.
  675. return False
  676. class RadioSelect(ChoiceWidget):
  677. input_type = "radio"
  678. template_name = "django/forms/widgets/radio.html"
  679. option_template_name = "django/forms/widgets/radio_option.html"
  680. use_fieldset = True
  681. def id_for_label(self, id_, index=None):
  682. """
  683. Don't include for="field_0" in <label> to improve accessibility when
  684. using a screen reader, in addition clicking such a label would toggle
  685. the first input.
  686. """
  687. if index is None:
  688. return ""
  689. return super().id_for_label(id_, index)
  690. class CheckboxSelectMultiple(RadioSelect):
  691. allow_multiple_selected = True
  692. input_type = "checkbox"
  693. template_name = "django/forms/widgets/checkbox_select.html"
  694. option_template_name = "django/forms/widgets/checkbox_option.html"
  695. def use_required_attribute(self, initial):
  696. # Don't use the 'required' attribute because browser validation would
  697. # require all checkboxes to be checked instead of at least one.
  698. return False
  699. def value_omitted_from_data(self, data, files, name):
  700. # HTML checkboxes don't appear in POST data if not checked, so it's
  701. # never known if the value is actually omitted.
  702. return False
  703. class MultiWidget(Widget):
  704. """
  705. A widget that is composed of multiple widgets.
  706. In addition to the values added by Widget.get_context(), this widget
  707. adds a list of subwidgets to the context as widget['subwidgets'].
  708. These can be looped over and rendered like normal widgets.
  709. You'll probably want to use this class with MultiValueField.
  710. """
  711. template_name = "django/forms/widgets/multiwidget.html"
  712. use_fieldset = True
  713. def __init__(self, widgets, attrs=None):
  714. if isinstance(widgets, dict):
  715. self.widgets_names = [("_%s" % name) if name else "" for name in widgets]
  716. widgets = widgets.values()
  717. else:
  718. self.widgets_names = ["_%s" % i for i in range(len(widgets))]
  719. self.widgets = [w() if isinstance(w, type) else w for w in widgets]
  720. super().__init__(attrs)
  721. @property
  722. def is_hidden(self):
  723. return all(w.is_hidden for w in self.widgets)
  724. def get_context(self, name, value, attrs):
  725. context = super().get_context(name, value, attrs)
  726. if self.is_localized:
  727. for widget in self.widgets:
  728. widget.is_localized = self.is_localized
  729. # value is a list/tuple of values, each corresponding to a widget
  730. # in self.widgets.
  731. if not isinstance(value, (list, tuple)):
  732. value = self.decompress(value)
  733. final_attrs = context["widget"]["attrs"]
  734. input_type = final_attrs.pop("type", None)
  735. id_ = final_attrs.get("id")
  736. subwidgets = []
  737. for i, (widget_name, widget) in enumerate(
  738. zip(self.widgets_names, self.widgets)
  739. ):
  740. if input_type is not None:
  741. widget.input_type = input_type
  742. widget_name = name + widget_name
  743. try:
  744. widget_value = value[i]
  745. except IndexError:
  746. widget_value = None
  747. if id_:
  748. widget_attrs = final_attrs.copy()
  749. widget_attrs["id"] = "%s_%s" % (id_, i)
  750. else:
  751. widget_attrs = final_attrs
  752. subwidgets.append(
  753. widget.get_context(widget_name, widget_value, widget_attrs)["widget"]
  754. )
  755. context["widget"]["subwidgets"] = subwidgets
  756. return context
  757. def id_for_label(self, id_):
  758. return ""
  759. def value_from_datadict(self, data, files, name):
  760. return [
  761. widget.value_from_datadict(data, files, name + widget_name)
  762. for widget_name, widget in zip(self.widgets_names, self.widgets)
  763. ]
  764. def value_omitted_from_data(self, data, files, name):
  765. return all(
  766. widget.value_omitted_from_data(data, files, name + widget_name)
  767. for widget_name, widget in zip(self.widgets_names, self.widgets)
  768. )
  769. def decompress(self, value):
  770. """
  771. Return a list of decompressed values for the given compressed value.
  772. The given value can be assumed to be valid, but not necessarily
  773. non-empty.
  774. """
  775. raise NotImplementedError("Subclasses must implement this method.")
  776. def _get_media(self):
  777. """
  778. Media for a multiwidget is the combination of all media of the
  779. subwidgets.
  780. """
  781. media = Media()
  782. for w in self.widgets:
  783. media = media + w.media
  784. return media
  785. media = property(_get_media)
  786. def __deepcopy__(self, memo):
  787. obj = super().__deepcopy__(memo)
  788. obj.widgets = copy.deepcopy(self.widgets)
  789. return obj
  790. @property
  791. def needs_multipart_form(self):
  792. return any(w.needs_multipart_form for w in self.widgets)
  793. class SplitDateTimeWidget(MultiWidget):
  794. """
  795. A widget that splits datetime input into two <input type="text"> boxes.
  796. """
  797. supports_microseconds = False
  798. template_name = "django/forms/widgets/splitdatetime.html"
  799. def __init__(
  800. self,
  801. attrs=None,
  802. date_format=None,
  803. time_format=None,
  804. date_attrs=None,
  805. time_attrs=None,
  806. ):
  807. widgets = (
  808. DateInput(
  809. attrs=attrs if date_attrs is None else date_attrs,
  810. format=date_format,
  811. ),
  812. TimeInput(
  813. attrs=attrs if time_attrs is None else time_attrs,
  814. format=time_format,
  815. ),
  816. )
  817. super().__init__(widgets)
  818. def decompress(self, value):
  819. if value:
  820. value = to_current_timezone(value)
  821. return [value.date(), value.time()]
  822. return [None, None]
  823. class SplitHiddenDateTimeWidget(SplitDateTimeWidget):
  824. """
  825. A widget that splits datetime input into two <input type="hidden"> inputs.
  826. """
  827. template_name = "django/forms/widgets/splithiddendatetime.html"
  828. def __init__(
  829. self,
  830. attrs=None,
  831. date_format=None,
  832. time_format=None,
  833. date_attrs=None,
  834. time_attrs=None,
  835. ):
  836. super().__init__(attrs, date_format, time_format, date_attrs, time_attrs)
  837. for widget in self.widgets:
  838. widget.input_type = "hidden"
  839. class SelectDateWidget(Widget):
  840. """
  841. A widget that splits date input into three <select> boxes.
  842. This also serves as an example of a Widget that has more than one HTML
  843. element and hence implements value_from_datadict.
  844. """
  845. none_value = ("", "---")
  846. month_field = "%s_month"
  847. day_field = "%s_day"
  848. year_field = "%s_year"
  849. template_name = "django/forms/widgets/select_date.html"
  850. input_type = "select"
  851. select_widget = Select
  852. date_re = _lazy_re_compile(r"(\d{4}|0)-(\d\d?)-(\d\d?)$")
  853. use_fieldset = True
  854. def __init__(self, attrs=None, years=None, months=None, empty_label=None):
  855. self.attrs = attrs or {}
  856. # Optional list or tuple of years to use in the "year" select box.
  857. if years:
  858. self.years = years
  859. else:
  860. this_year = datetime.date.today().year
  861. self.years = range(this_year, this_year + 10)
  862. # Optional dict of months to use in the "month" select box.
  863. if months:
  864. self.months = months
  865. else:
  866. self.months = MONTHS
  867. # Optional string, list, or tuple to use as empty_label.
  868. if isinstance(empty_label, (list, tuple)):
  869. if not len(empty_label) == 3:
  870. raise ValueError("empty_label list/tuple must have 3 elements.")
  871. self.year_none_value = ("", empty_label[0])
  872. self.month_none_value = ("", empty_label[1])
  873. self.day_none_value = ("", empty_label[2])
  874. else:
  875. if empty_label is not None:
  876. self.none_value = ("", empty_label)
  877. self.year_none_value = self.none_value
  878. self.month_none_value = self.none_value
  879. self.day_none_value = self.none_value
  880. def get_context(self, name, value, attrs):
  881. context = super().get_context(name, value, attrs)
  882. date_context = {}
  883. year_choices = [(i, str(i)) for i in self.years]
  884. if not self.is_required:
  885. year_choices.insert(0, self.year_none_value)
  886. year_name = self.year_field % name
  887. date_context["year"] = self.select_widget(
  888. attrs, choices=year_choices
  889. ).get_context(
  890. name=year_name,
  891. value=context["widget"]["value"]["year"],
  892. attrs={**context["widget"]["attrs"], "id": "id_%s" % year_name},
  893. )
  894. month_choices = list(self.months.items())
  895. if not self.is_required:
  896. month_choices.insert(0, self.month_none_value)
  897. month_name = self.month_field % name
  898. date_context["month"] = self.select_widget(
  899. attrs, choices=month_choices
  900. ).get_context(
  901. name=month_name,
  902. value=context["widget"]["value"]["month"],
  903. attrs={**context["widget"]["attrs"], "id": "id_%s" % month_name},
  904. )
  905. day_choices = [(i, i) for i in range(1, 32)]
  906. if not self.is_required:
  907. day_choices.insert(0, self.day_none_value)
  908. day_name = self.day_field % name
  909. date_context["day"] = self.select_widget(
  910. attrs,
  911. choices=day_choices,
  912. ).get_context(
  913. name=day_name,
  914. value=context["widget"]["value"]["day"],
  915. attrs={**context["widget"]["attrs"], "id": "id_%s" % day_name},
  916. )
  917. subwidgets = []
  918. for field in self._parse_date_fmt():
  919. subwidgets.append(date_context[field]["widget"])
  920. context["widget"]["subwidgets"] = subwidgets
  921. return context
  922. def format_value(self, value):
  923. """
  924. Return a dict containing the year, month, and day of the current value.
  925. Use dict instead of a datetime to allow invalid dates such as February
  926. 31 to display correctly.
  927. """
  928. year, month, day = None, None, None
  929. if isinstance(value, (datetime.date, datetime.datetime)):
  930. year, month, day = value.year, value.month, value.day
  931. elif isinstance(value, str):
  932. match = self.date_re.match(value)
  933. if match:
  934. # Convert any zeros in the date to empty strings to match the
  935. # empty option value.
  936. year, month, day = [int(val) or "" for val in match.groups()]
  937. else:
  938. input_format = get_format("DATE_INPUT_FORMATS")[0]
  939. try:
  940. d = datetime.datetime.strptime(value, input_format)
  941. except ValueError:
  942. pass
  943. else:
  944. year, month, day = d.year, d.month, d.day
  945. return {"year": year, "month": month, "day": day}
  946. @staticmethod
  947. def _parse_date_fmt():
  948. fmt = get_format("DATE_FORMAT")
  949. escaped = False
  950. for char in fmt:
  951. if escaped:
  952. escaped = False
  953. elif char == "\\":
  954. escaped = True
  955. elif char in "Yy":
  956. yield "year"
  957. elif char in "bEFMmNn":
  958. yield "month"
  959. elif char in "dj":
  960. yield "day"
  961. def id_for_label(self, id_):
  962. for first_select in self._parse_date_fmt():
  963. return "%s_%s" % (id_, first_select)
  964. return "%s_month" % id_
  965. def value_from_datadict(self, data, files, name):
  966. y = data.get(self.year_field % name)
  967. m = data.get(self.month_field % name)
  968. d = data.get(self.day_field % name)
  969. if y == m == d == "":
  970. return None
  971. if y is not None and m is not None and d is not None:
  972. input_format = get_format("DATE_INPUT_FORMATS")[0]
  973. input_format = formats.sanitize_strftime_format(input_format)
  974. try:
  975. date_value = datetime.date(int(y), int(m), int(d))
  976. except ValueError:
  977. # Return pseudo-ISO dates with zeros for any unselected values,
  978. # e.g. '2017-0-23'.
  979. return "%s-%s-%s" % (y or 0, m or 0, d or 0)
  980. return date_value.strftime(input_format)
  981. return data.get(name)
  982. def value_omitted_from_data(self, data, files, name):
  983. return not any(
  984. ("{}_{}".format(name, interval) in data)
  985. for interval in ("year", "month", "day")
  986. )