You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

widgets.py 36KB

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