widgets.py 37 KB

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