widgets.py 39 KB

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