widgets.py 38 KB

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