widgets.py 42 KB

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