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 36 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. """
  2. HTML Widget classes
  3. """
  4. from __future__ import unicode_literals
  5. import copy
  6. import datetime
  7. import re
  8. from itertools import chain
  9. from django.conf import settings
  10. from django.forms.utils import flatatt, to_current_timezone
  11. from django.utils import datetime_safe, formats, six
  12. from django.utils.datastructures import MultiValueDict
  13. from django.utils.dates import MONTHS
  14. from django.utils.encoding import (
  15. force_str, force_text, python_2_unicode_compatible,
  16. )
  17. from django.utils.formats import get_format
  18. from django.utils.html import conditional_escape, format_html, html_safe
  19. from django.utils.safestring import mark_safe
  20. from django.utils.six.moves import range
  21. from django.utils.six.moves.urllib.parse import urljoin
  22. from django.utils.translation import ugettext_lazy
  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. @html_safe
  34. @python_2_unicode_compatible
  35. class Media(object):
  36. def __init__(self, media=None, **kwargs):
  37. if media:
  38. media_attrs = media.__dict__
  39. else:
  40. media_attrs = kwargs
  41. self._css = {}
  42. self._js = []
  43. for name in MEDIA_TYPES:
  44. getattr(self, 'add_' + name)(media_attrs.get(name))
  45. def __str__(self):
  46. return self.render()
  47. def render(self):
  48. return mark_safe('\n'.join(chain(*[getattr(self, 'render_' + name)() for name in MEDIA_TYPES])))
  49. def render_js(self):
  50. return [
  51. format_html(
  52. '<script type="text/javascript" src="{}"></script>',
  53. self.absolute_path(path)
  54. ) for path in self._js
  55. ]
  56. def render_css(self):
  57. # To keep rendering order consistent, we can't just iterate over items().
  58. # We need to sort the keys, and iterate over the sorted list.
  59. media = sorted(self._css.keys())
  60. return chain(*[[
  61. format_html(
  62. '<link href="{}" type="text/css" media="{}" rel="stylesheet" />',
  63. self.absolute_path(path), medium
  64. ) for path in self._css[medium]
  65. ] for medium in media])
  66. def absolute_path(self, path, prefix=None):
  67. if path.startswith(('http://', 'https://', '/')):
  68. return path
  69. if prefix is None:
  70. if settings.STATIC_URL is None:
  71. # backwards compatibility
  72. prefix = settings.MEDIA_URL
  73. else:
  74. prefix = settings.STATIC_URL
  75. return urljoin(prefix, path)
  76. def __getitem__(self, name):
  77. "Returns a Media object that only contains media of the given type"
  78. if name in MEDIA_TYPES:
  79. return Media(**{str(name): getattr(self, '_' + name)})
  80. raise KeyError('Unknown media type "%s"' % name)
  81. def add_js(self, data):
  82. if data:
  83. for path in data:
  84. if path not in self._js:
  85. self._js.append(path)
  86. def add_css(self, data):
  87. if data:
  88. for medium, paths in data.items():
  89. for path in paths:
  90. if not self._css.get(medium) or path not in self._css[medium]:
  91. self._css.setdefault(medium, []).append(path)
  92. def __add__(self, other):
  93. combined = Media()
  94. for name in MEDIA_TYPES:
  95. getattr(combined, 'add_' + name)(getattr(self, '_' + name, None))
  96. getattr(combined, 'add_' + name)(getattr(other, '_' + name, None))
  97. return combined
  98. def media_property(cls):
  99. def _media(self):
  100. # Get the media property of the superclass, if it exists
  101. sup_cls = super(cls, self)
  102. try:
  103. base = sup_cls.media
  104. except AttributeError:
  105. base = Media()
  106. # Get the media definition for this class
  107. definition = getattr(cls, 'Media', None)
  108. if definition:
  109. extend = getattr(definition, 'extend', True)
  110. if extend:
  111. if extend is True:
  112. m = base
  113. else:
  114. m = Media()
  115. for medium in extend:
  116. m = m + base[medium]
  117. return m + Media(definition)
  118. else:
  119. return Media(definition)
  120. else:
  121. return base
  122. return property(_media)
  123. class MediaDefiningClass(type):
  124. """
  125. Metaclass for classes that can have media definitions.
  126. """
  127. def __new__(mcs, name, bases, attrs):
  128. new_class = (super(MediaDefiningClass, mcs)
  129. .__new__(mcs, name, bases, attrs))
  130. if 'media' not in attrs:
  131. new_class.media = media_property(new_class)
  132. return new_class
  133. @html_safe
  134. @python_2_unicode_compatible
  135. class SubWidget(object):
  136. """
  137. Some widgets are made of multiple HTML elements -- namely, RadioSelect.
  138. This is a class that represents the "inner" HTML element of a widget.
  139. """
  140. def __init__(self, parent_widget, name, value, attrs, choices):
  141. self.parent_widget = parent_widget
  142. self.name, self.value = name, value
  143. self.attrs, self.choices = attrs, choices
  144. def __str__(self):
  145. args = [self.name, self.value, self.attrs]
  146. if self.choices:
  147. args.append(self.choices)
  148. return self.parent_widget.render(*args)
  149. class Widget(six.with_metaclass(MediaDefiningClass)):
  150. needs_multipart_form = False # Determines does this widget need multipart form
  151. is_localized = False
  152. is_required = False
  153. supports_microseconds = True
  154. def __init__(self, attrs=None):
  155. if attrs is not None:
  156. self.attrs = attrs.copy()
  157. else:
  158. self.attrs = {}
  159. def __deepcopy__(self, memo):
  160. obj = copy.copy(self)
  161. obj.attrs = self.attrs.copy()
  162. memo[id(self)] = obj
  163. return obj
  164. @property
  165. def is_hidden(self):
  166. return self.input_type == 'hidden' if hasattr(self, 'input_type') else False
  167. def subwidgets(self, name, value, attrs=None, choices=()):
  168. """
  169. Yields all "subwidgets" of this widget. Used only by RadioSelect to
  170. allow template access to individual <input type="radio"> buttons.
  171. Arguments are the same as for render().
  172. """
  173. yield SubWidget(self, name, value, attrs, choices)
  174. def render(self, name, value, attrs=None):
  175. """
  176. Returns this Widget rendered as HTML, as a Unicode string.
  177. The 'value' given is not guaranteed to be valid input, so subclass
  178. implementations should program defensively.
  179. """
  180. raise NotImplementedError('subclasses of Widget must provide a render() method')
  181. def build_attrs(self, extra_attrs=None, **kwargs):
  182. "Helper function for building an attribute dictionary."
  183. attrs = dict(self.attrs, **kwargs)
  184. if extra_attrs:
  185. attrs.update(extra_attrs)
  186. return attrs
  187. def value_from_datadict(self, data, files, name):
  188. """
  189. Given a dictionary of data and this widget's name, returns the value
  190. of this widget. Returns None if it's not provided.
  191. """
  192. return data.get(name)
  193. def id_for_label(self, id_):
  194. """
  195. Returns the HTML ID attribute of this Widget for use by a <label>,
  196. given the ID of the field. Returns None if no ID is available.
  197. This hook is necessary because some widgets have multiple HTML
  198. elements and, thus, multiple IDs. In that case, this method should
  199. return an ID value that corresponds to the first ID in the widget's
  200. tags.
  201. """
  202. return id_
  203. class Input(Widget):
  204. """
  205. Base class for all <input> widgets (except type='checkbox' and
  206. type='radio', which are special).
  207. """
  208. input_type = None # Subclasses must define this.
  209. def _format_value(self, value):
  210. if self.is_localized:
  211. return formats.localize_input(value)
  212. return value
  213. def render(self, name, value, attrs=None):
  214. if value is None:
  215. value = ''
  216. final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
  217. if value != '':
  218. # Only add the 'value' attribute if a value is non-empty.
  219. final_attrs['value'] = force_text(self._format_value(value))
  220. return format_html('<input{} />', flatatt(final_attrs))
  221. class TextInput(Input):
  222. input_type = 'text'
  223. def __init__(self, attrs=None):
  224. if attrs is not None:
  225. self.input_type = attrs.pop('type', self.input_type)
  226. super(TextInput, self).__init__(attrs)
  227. class NumberInput(TextInput):
  228. input_type = 'number'
  229. class EmailInput(TextInput):
  230. input_type = 'email'
  231. class URLInput(TextInput):
  232. input_type = 'url'
  233. class PasswordInput(TextInput):
  234. input_type = 'password'
  235. def __init__(self, attrs=None, render_value=False):
  236. super(PasswordInput, self).__init__(attrs)
  237. self.render_value = render_value
  238. def render(self, name, value, attrs=None):
  239. if not self.render_value:
  240. value = None
  241. return super(PasswordInput, self).render(name, value, attrs)
  242. class HiddenInput(Input):
  243. input_type = 'hidden'
  244. class MultipleHiddenInput(HiddenInput):
  245. """
  246. A widget that handles <input type="hidden"> for fields that have a list
  247. of values.
  248. """
  249. def __init__(self, attrs=None, choices=()):
  250. super(MultipleHiddenInput, self).__init__(attrs)
  251. # choices can be any iterable
  252. self.choices = choices
  253. def render(self, name, value, attrs=None, choices=()):
  254. if value is None:
  255. value = []
  256. final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
  257. id_ = final_attrs.get('id')
  258. inputs = []
  259. for i, v in enumerate(value):
  260. input_attrs = dict(value=force_text(v), **final_attrs)
  261. if id_:
  262. # An ID attribute was given. Add a numeric index as a suffix
  263. # so that the inputs don't all have the same ID attribute.
  264. input_attrs['id'] = '%s_%s' % (id_, i)
  265. inputs.append(format_html('<input{} />', flatatt(input_attrs)))
  266. return mark_safe('\n'.join(inputs))
  267. def value_from_datadict(self, data, files, name):
  268. if isinstance(data, MultiValueDict):
  269. return data.getlist(name)
  270. return data.get(name)
  271. class FileInput(Input):
  272. input_type = 'file'
  273. needs_multipart_form = True
  274. def render(self, name, value, attrs=None):
  275. return super(FileInput, self).render(name, None, attrs=attrs)
  276. def value_from_datadict(self, data, files, name):
  277. "File widgets take data from FILES, not POST"
  278. return files.get(name)
  279. FILE_INPUT_CONTRADICTION = object()
  280. class ClearableFileInput(FileInput):
  281. initial_text = ugettext_lazy('Currently')
  282. input_text = ugettext_lazy('Change')
  283. clear_checkbox_label = ugettext_lazy('Clear')
  284. template_with_initial = (
  285. '%(initial_text)s: <a href="%(initial_url)s">%(initial)s</a> '
  286. '%(clear_template)s<br />%(input_text)s: %(input)s'
  287. )
  288. template_with_clear = '%(clear)s <label for="%(clear_checkbox_id)s">%(clear_checkbox_label)s</label>'
  289. def clear_checkbox_name(self, name):
  290. """
  291. Given the name of the file input, return the name of the clear checkbox
  292. input.
  293. """
  294. return name + '-clear'
  295. def clear_checkbox_id(self, name):
  296. """
  297. Given the name of the clear checkbox input, return the HTML id for it.
  298. """
  299. return name + '_id'
  300. def is_initial(self, value):
  301. """
  302. Return whether value is considered to be initial value.
  303. """
  304. return bool(value and hasattr(value, 'url'))
  305. def get_template_substitution_values(self, value):
  306. """
  307. Return value-related substitutions.
  308. """
  309. return {
  310. 'initial': conditional_escape(value),
  311. 'initial_url': conditional_escape(value.url),
  312. }
  313. def render(self, name, value, attrs=None):
  314. substitutions = {
  315. 'initial_text': self.initial_text,
  316. 'input_text': self.input_text,
  317. 'clear_template': '',
  318. 'clear_checkbox_label': self.clear_checkbox_label,
  319. }
  320. template = '%(input)s'
  321. substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)
  322. if self.is_initial(value):
  323. template = self.template_with_initial
  324. substitutions.update(self.get_template_substitution_values(value))
  325. if not self.is_required:
  326. checkbox_name = self.clear_checkbox_name(name)
  327. checkbox_id = self.clear_checkbox_id(checkbox_name)
  328. substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)
  329. substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)
  330. substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
  331. substitutions['clear_template'] = self.template_with_clear % substitutions
  332. return mark_safe(template % substitutions)
  333. def value_from_datadict(self, data, files, name):
  334. upload = super(ClearableFileInput, self).value_from_datadict(data, files, name)
  335. if not self.is_required and CheckboxInput().value_from_datadict(
  336. data, files, self.clear_checkbox_name(name)):
  337. if upload:
  338. # If the user contradicts themselves (uploads a new file AND
  339. # checks the "clear" checkbox), we return a unique marker
  340. # object that FileField will turn into a ValidationError.
  341. return FILE_INPUT_CONTRADICTION
  342. # False signals to clear any existing value, as opposed to just None
  343. return False
  344. return upload
  345. class Textarea(Widget):
  346. def __init__(self, attrs=None):
  347. # Use slightly better defaults than HTML's 20x2 box
  348. default_attrs = {'cols': '40', 'rows': '10'}
  349. if attrs:
  350. default_attrs.update(attrs)
  351. super(Textarea, self).__init__(default_attrs)
  352. def render(self, name, value, attrs=None):
  353. if value is None:
  354. value = ''
  355. final_attrs = self.build_attrs(attrs, name=name)
  356. return format_html('<textarea{}>\r\n{}</textarea>',
  357. flatatt(final_attrs),
  358. force_text(value))
  359. class DateTimeBaseInput(TextInput):
  360. format_key = ''
  361. supports_microseconds = False
  362. def __init__(self, attrs=None, format=None):
  363. super(DateTimeBaseInput, self).__init__(attrs)
  364. self.format = format if format else None
  365. def _format_value(self, value):
  366. return formats.localize_input(value,
  367. self.format or formats.get_format(self.format_key)[0])
  368. class DateInput(DateTimeBaseInput):
  369. format_key = 'DATE_INPUT_FORMATS'
  370. class DateTimeInput(DateTimeBaseInput):
  371. format_key = 'DATETIME_INPUT_FORMATS'
  372. class TimeInput(DateTimeBaseInput):
  373. format_key = 'TIME_INPUT_FORMATS'
  374. # Defined at module level so that CheckboxInput is picklable (#17976)
  375. def boolean_check(v):
  376. return not (v is False or v is None or v == '')
  377. class CheckboxInput(Widget):
  378. def __init__(self, attrs=None, check_test=None):
  379. super(CheckboxInput, self).__init__(attrs)
  380. # check_test is a callable that takes a value and returns True
  381. # if the checkbox should be checked for that value.
  382. self.check_test = boolean_check if check_test is None else check_test
  383. def render(self, name, value, attrs=None):
  384. final_attrs = self.build_attrs(attrs, type='checkbox', name=name)
  385. if self.check_test(value):
  386. final_attrs['checked'] = 'checked'
  387. if not (value is True or value is False or value is None or value == ''):
  388. # Only add the 'value' attribute if a value is non-empty.
  389. final_attrs['value'] = force_text(value)
  390. return format_html('<input{} />', flatatt(final_attrs))
  391. def value_from_datadict(self, data, files, name):
  392. if name not in data:
  393. # A missing value means False because HTML form submission does not
  394. # send results for unselected checkboxes.
  395. return False
  396. value = data.get(name)
  397. # Translate true and false strings to boolean values.
  398. values = {'true': True, 'false': False}
  399. if isinstance(value, six.string_types):
  400. value = values.get(value.lower(), value)
  401. return bool(value)
  402. class Select(Widget):
  403. allow_multiple_selected = False
  404. def __init__(self, attrs=None, choices=()):
  405. super(Select, self).__init__(attrs)
  406. # choices can be any iterable, but we may need to render this widget
  407. # multiple times. Thus, collapse it into a list so it can be consumed
  408. # more than once.
  409. self.choices = list(choices)
  410. def __deepcopy__(self, memo):
  411. obj = copy.copy(self)
  412. obj.attrs = self.attrs.copy()
  413. obj.choices = copy.copy(self.choices)
  414. memo[id(self)] = obj
  415. return obj
  416. def render(self, name, value, attrs=None, choices=()):
  417. if value is None:
  418. value = ''
  419. final_attrs = self.build_attrs(attrs, name=name)
  420. output = [format_html('<select{}>', flatatt(final_attrs))]
  421. options = self.render_options(choices, [value])
  422. if options:
  423. output.append(options)
  424. output.append('</select>')
  425. return mark_safe('\n'.join(output))
  426. def render_option(self, selected_choices, option_value, option_label):
  427. if option_value is None:
  428. option_value = ''
  429. option_value = force_text(option_value)
  430. if option_value in selected_choices:
  431. selected_html = mark_safe(' selected="selected"')
  432. if not self.allow_multiple_selected:
  433. # Only allow for a single selection.
  434. selected_choices.remove(option_value)
  435. else:
  436. selected_html = ''
  437. return format_html('<option value="{}"{}>{}</option>',
  438. option_value,
  439. selected_html,
  440. force_text(option_label))
  441. def render_options(self, choices, selected_choices):
  442. # Normalize to strings.
  443. selected_choices = set(force_text(v) for v in selected_choices)
  444. output = []
  445. for option_value, option_label in chain(self.choices, choices):
  446. if isinstance(option_label, (list, tuple)):
  447. output.append(format_html('<optgroup label="{}">', force_text(option_value)))
  448. for option in option_label:
  449. output.append(self.render_option(selected_choices, *option))
  450. output.append('</optgroup>')
  451. else:
  452. output.append(self.render_option(selected_choices, option_value, option_label))
  453. return '\n'.join(output)
  454. class NullBooleanSelect(Select):
  455. """
  456. A Select Widget intended to be used with NullBooleanField.
  457. """
  458. def __init__(self, attrs=None):
  459. choices = (('1', ugettext_lazy('Unknown')),
  460. ('2', ugettext_lazy('Yes')),
  461. ('3', ugettext_lazy('No')))
  462. super(NullBooleanSelect, self).__init__(attrs, choices)
  463. def render(self, name, value, attrs=None, choices=()):
  464. try:
  465. value = {True: '2', False: '3', '2': '2', '3': '3'}[value]
  466. except KeyError:
  467. value = '1'
  468. return super(NullBooleanSelect, self).render(name, value, attrs, choices)
  469. def value_from_datadict(self, data, files, name):
  470. value = data.get(name)
  471. return {'2': True,
  472. True: True,
  473. 'True': True,
  474. '3': False,
  475. 'False': False,
  476. False: False}.get(value)
  477. class SelectMultiple(Select):
  478. allow_multiple_selected = True
  479. def render(self, name, value, attrs=None, choices=()):
  480. if value is None:
  481. value = []
  482. final_attrs = self.build_attrs(attrs, name=name)
  483. output = [format_html('<select multiple="multiple"{}>', flatatt(final_attrs))]
  484. options = self.render_options(choices, value)
  485. if options:
  486. output.append(options)
  487. output.append('</select>')
  488. return mark_safe('\n'.join(output))
  489. def value_from_datadict(self, data, files, name):
  490. if isinstance(data, MultiValueDict):
  491. return data.getlist(name)
  492. return data.get(name)
  493. @html_safe
  494. @python_2_unicode_compatible
  495. class ChoiceInput(SubWidget):
  496. """
  497. An object used by ChoiceFieldRenderer that represents a single
  498. <input type='$input_type'>.
  499. """
  500. input_type = None # Subclasses must define this
  501. def __init__(self, name, value, attrs, choice, index):
  502. self.name = name
  503. self.value = value
  504. self.attrs = attrs
  505. self.choice_value = force_text(choice[0])
  506. self.choice_label = force_text(choice[1])
  507. self.index = index
  508. if 'id' in self.attrs:
  509. self.attrs['id'] += "_%d" % self.index
  510. def __str__(self):
  511. return self.render()
  512. def render(self, name=None, value=None, attrs=None, choices=()):
  513. if self.id_for_label:
  514. label_for = format_html(' for="{}"', self.id_for_label)
  515. else:
  516. label_for = ''
  517. attrs = dict(self.attrs, **attrs) if attrs else self.attrs
  518. return format_html(
  519. '<label{}>{} {}</label>', label_for, self.tag(attrs), self.choice_label
  520. )
  521. def is_checked(self):
  522. return self.value == self.choice_value
  523. def tag(self, attrs=None):
  524. attrs = attrs or self.attrs
  525. final_attrs = dict(attrs, type=self.input_type, name=self.name, value=self.choice_value)
  526. if self.is_checked():
  527. final_attrs['checked'] = 'checked'
  528. return format_html('<input{} />', flatatt(final_attrs))
  529. @property
  530. def id_for_label(self):
  531. return self.attrs.get('id', '')
  532. class RadioChoiceInput(ChoiceInput):
  533. input_type = 'radio'
  534. def __init__(self, *args, **kwargs):
  535. super(RadioChoiceInput, self).__init__(*args, **kwargs)
  536. self.value = force_text(self.value)
  537. class CheckboxChoiceInput(ChoiceInput):
  538. input_type = 'checkbox'
  539. def __init__(self, *args, **kwargs):
  540. super(CheckboxChoiceInput, self).__init__(*args, **kwargs)
  541. self.value = set(force_text(v) for v in self.value)
  542. def is_checked(self):
  543. return self.choice_value in self.value
  544. @html_safe
  545. @python_2_unicode_compatible
  546. class ChoiceFieldRenderer(object):
  547. """
  548. An object used by RadioSelect to enable customization of radio widgets.
  549. """
  550. choice_input_class = None
  551. outer_html = '<ul{id_attr}>{content}</ul>'
  552. inner_html = '<li>{choice_value}{sub_widgets}</li>'
  553. def __init__(self, name, value, attrs, choices):
  554. self.name = name
  555. self.value = value
  556. self.attrs = attrs
  557. self.choices = choices
  558. def __getitem__(self, idx):
  559. choice = self.choices[idx] # Let the IndexError propagate
  560. return self.choice_input_class(self.name, self.value, self.attrs.copy(), choice, idx)
  561. def __str__(self):
  562. return self.render()
  563. def render(self):
  564. """
  565. Outputs a <ul> for this set of choice fields.
  566. If an id was given to the field, it is applied to the <ul> (each
  567. item in the list will get an id of `$id_$i`).
  568. """
  569. id_ = self.attrs.get('id')
  570. output = []
  571. for i, choice in enumerate(self.choices):
  572. choice_value, choice_label = choice
  573. if isinstance(choice_label, (tuple, list)):
  574. attrs_plus = self.attrs.copy()
  575. if id_:
  576. attrs_plus['id'] += '_{}'.format(i)
  577. sub_ul_renderer = self.__class__(
  578. name=self.name,
  579. value=self.value,
  580. attrs=attrs_plus,
  581. choices=choice_label,
  582. )
  583. sub_ul_renderer.choice_input_class = self.choice_input_class
  584. output.append(format_html(self.inner_html, choice_value=choice_value,
  585. sub_widgets=sub_ul_renderer.render()))
  586. else:
  587. w = self.choice_input_class(self.name, self.value,
  588. self.attrs.copy(), choice, i)
  589. output.append(format_html(self.inner_html,
  590. choice_value=force_text(w), sub_widgets=''))
  591. return format_html(self.outer_html,
  592. id_attr=format_html(' id="{}"', id_) if id_ else '',
  593. content=mark_safe('\n'.join(output)))
  594. class RadioFieldRenderer(ChoiceFieldRenderer):
  595. choice_input_class = RadioChoiceInput
  596. class CheckboxFieldRenderer(ChoiceFieldRenderer):
  597. choice_input_class = CheckboxChoiceInput
  598. class RendererMixin(object):
  599. renderer = None # subclasses must define this
  600. _empty_value = None
  601. def __init__(self, *args, **kwargs):
  602. # Override the default renderer if we were passed one.
  603. renderer = kwargs.pop('renderer', None)
  604. if renderer:
  605. self.renderer = renderer
  606. super(RendererMixin, self).__init__(*args, **kwargs)
  607. def subwidgets(self, name, value, attrs=None, choices=()):
  608. for widget in self.get_renderer(name, value, attrs, choices):
  609. yield widget
  610. def get_renderer(self, name, value, attrs=None, choices=()):
  611. """Returns an instance of the renderer."""
  612. if value is None:
  613. value = self._empty_value
  614. final_attrs = self.build_attrs(attrs)
  615. choices = list(chain(self.choices, choices))
  616. return self.renderer(name, value, final_attrs, choices)
  617. def render(self, name, value, attrs=None, choices=()):
  618. return self.get_renderer(name, value, attrs, choices).render()
  619. def id_for_label(self, id_):
  620. # Widgets using this RendererMixin are made of a collection of
  621. # subwidgets, each with their own <label>, and distinct ID.
  622. # The IDs are made distinct by y "_X" suffix, where X is the zero-based
  623. # index of the choice field. Thus, the label for the main widget should
  624. # reference the first subwidget, hence the "_0" suffix.
  625. if id_:
  626. id_ += '_0'
  627. return id_
  628. class RadioSelect(RendererMixin, Select):
  629. renderer = RadioFieldRenderer
  630. _empty_value = ''
  631. class CheckboxSelectMultiple(RendererMixin, SelectMultiple):
  632. renderer = CheckboxFieldRenderer
  633. _empty_value = []
  634. class MultiWidget(Widget):
  635. """
  636. A widget that is composed of multiple widgets.
  637. Its render() method is different than other widgets', because it has to
  638. figure out how to split a single value for display in multiple widgets.
  639. The ``value`` argument can be one of two things:
  640. * A list.
  641. * A normal value (e.g., a string) that has been "compressed" from
  642. a list of values.
  643. In the second case -- i.e., if the value is NOT a list -- render() will
  644. first "decompress" the value into a list before rendering it. It does so by
  645. calling the decompress() method, which MultiWidget subclasses must
  646. implement. This method takes a single "compressed" value and returns a
  647. list.
  648. When render() does its HTML rendering, each value in the list is rendered
  649. with the corresponding widget -- the first value is rendered in the first
  650. widget, the second value is rendered in the second widget, etc.
  651. Subclasses may implement format_output(), which takes the list of rendered
  652. widgets and returns a string of HTML that formats them any way you'd like.
  653. You'll probably want to use this class with MultiValueField.
  654. """
  655. def __init__(self, widgets, attrs=None):
  656. self.widgets = [w() if isinstance(w, type) else w for w in widgets]
  657. super(MultiWidget, self).__init__(attrs)
  658. @property
  659. def is_hidden(self):
  660. return all(w.is_hidden for w in self.widgets)
  661. def render(self, name, value, attrs=None):
  662. if self.is_localized:
  663. for widget in self.widgets:
  664. widget.is_localized = self.is_localized
  665. # value is a list of values, each corresponding to a widget
  666. # in self.widgets.
  667. if not isinstance(value, list):
  668. value = self.decompress(value)
  669. output = []
  670. final_attrs = self.build_attrs(attrs)
  671. id_ = final_attrs.get('id')
  672. for i, widget in enumerate(self.widgets):
  673. try:
  674. widget_value = value[i]
  675. except IndexError:
  676. widget_value = None
  677. if id_:
  678. final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
  679. output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
  680. return mark_safe(self.format_output(output))
  681. def id_for_label(self, id_):
  682. # See the comment for RadioSelect.id_for_label()
  683. if id_:
  684. id_ += '_0'
  685. return id_
  686. def value_from_datadict(self, data, files, name):
  687. return [widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)]
  688. def format_output(self, rendered_widgets):
  689. """
  690. Given a list of rendered widgets (as strings), returns a Unicode string
  691. representing the HTML for the whole lot.
  692. This hook allows you to format the HTML design of the widgets, if
  693. needed.
  694. """
  695. return ''.join(rendered_widgets)
  696. def decompress(self, value):
  697. """
  698. Returns a list of decompressed values for the given compressed value.
  699. The given value can be assumed to be valid, but not necessarily
  700. non-empty.
  701. """
  702. raise NotImplementedError('Subclasses must implement this method.')
  703. def _get_media(self):
  704. "Media for a multiwidget is the combination of all media of the subwidgets"
  705. media = Media()
  706. for w in self.widgets:
  707. media = media + w.media
  708. return media
  709. media = property(_get_media)
  710. def __deepcopy__(self, memo):
  711. obj = super(MultiWidget, self).__deepcopy__(memo)
  712. obj.widgets = copy.deepcopy(self.widgets)
  713. return obj
  714. @property
  715. def needs_multipart_form(self):
  716. return any(w.needs_multipart_form for w in self.widgets)
  717. class SplitDateTimeWidget(MultiWidget):
  718. """
  719. A Widget that splits datetime input into two <input type="text"> boxes.
  720. """
  721. supports_microseconds = False
  722. def __init__(self, attrs=None, date_format=None, time_format=None):
  723. widgets = (DateInput(attrs=attrs, format=date_format),
  724. TimeInput(attrs=attrs, format=time_format))
  725. super(SplitDateTimeWidget, self).__init__(widgets, attrs)
  726. def decompress(self, value):
  727. if value:
  728. value = to_current_timezone(value)
  729. return [value.date(), value.time().replace(microsecond=0)]
  730. return [None, None]
  731. class SplitHiddenDateTimeWidget(SplitDateTimeWidget):
  732. """
  733. A Widget that splits datetime input into two <input type="hidden"> inputs.
  734. """
  735. def __init__(self, attrs=None, date_format=None, time_format=None):
  736. super(SplitHiddenDateTimeWidget, self).__init__(attrs, date_format, time_format)
  737. for widget in self.widgets:
  738. widget.input_type = 'hidden'
  739. class SelectDateWidget(Widget):
  740. """
  741. A Widget that splits date input into three <select> boxes.
  742. This also serves as an example of a Widget that has more than one HTML
  743. element and hence implements value_from_datadict.
  744. """
  745. none_value = (0, '---')
  746. month_field = '%s_month'
  747. day_field = '%s_day'
  748. year_field = '%s_year'
  749. select_widget = Select
  750. date_re = re.compile(r'(\d{4})-(\d\d?)-(\d\d?)$')
  751. def __init__(self, attrs=None, years=None, months=None, empty_label=None):
  752. self.attrs = attrs or {}
  753. # Optional list or tuple of years to use in the "year" select box.
  754. if years:
  755. self.years = years
  756. else:
  757. this_year = datetime.date.today().year
  758. self.years = range(this_year, this_year + 10)
  759. # Optional dict of months to use in the "month" select box.
  760. if months:
  761. self.months = months
  762. else:
  763. self.months = MONTHS
  764. # Optional string, list, or tuple to use as empty_label.
  765. if isinstance(empty_label, (list, tuple)):
  766. if not len(empty_label) == 3:
  767. raise ValueError('empty_label list/tuple must have 3 elements.')
  768. self.year_none_value = (0, empty_label[0])
  769. self.month_none_value = (0, empty_label[1])
  770. self.day_none_value = (0, empty_label[2])
  771. else:
  772. if empty_label is not None:
  773. self.none_value = (0, empty_label)
  774. self.year_none_value = self.none_value
  775. self.month_none_value = self.none_value
  776. self.day_none_value = self.none_value
  777. @staticmethod
  778. def _parse_date_fmt():
  779. fmt = get_format('DATE_FORMAT')
  780. escaped = False
  781. for char in fmt:
  782. if escaped:
  783. escaped = False
  784. elif char == '\\':
  785. escaped = True
  786. elif char in 'Yy':
  787. yield 'year'
  788. elif char in 'bEFMmNn':
  789. yield 'month'
  790. elif char in 'dj':
  791. yield 'day'
  792. def render(self, name, value, attrs=None):
  793. try:
  794. year_val, month_val, day_val = value.year, value.month, value.day
  795. except AttributeError:
  796. year_val = month_val = day_val = None
  797. if isinstance(value, six.string_types):
  798. if settings.USE_L10N:
  799. try:
  800. input_format = get_format('DATE_INPUT_FORMATS')[0]
  801. v = datetime.datetime.strptime(force_str(value), input_format)
  802. year_val, month_val, day_val = v.year, v.month, v.day
  803. except ValueError:
  804. pass
  805. if year_val is None:
  806. match = self.date_re.match(value)
  807. if match:
  808. year_val, month_val, day_val = [int(val) for val in match.groups()]
  809. html = {}
  810. choices = [(i, i) for i in self.years]
  811. html['year'] = self.create_select(name, self.year_field, value, year_val, choices, self.year_none_value)
  812. choices = list(self.months.items())
  813. html['month'] = self.create_select(name, self.month_field, value, month_val, choices, self.month_none_value)
  814. choices = [(i, i) for i in range(1, 32)]
  815. html['day'] = self.create_select(name, self.day_field, value, day_val, choices, self.day_none_value)
  816. output = []
  817. for field in self._parse_date_fmt():
  818. output.append(html[field])
  819. return mark_safe('\n'.join(output))
  820. def id_for_label(self, id_):
  821. for first_select in self._parse_date_fmt():
  822. return '%s_%s' % (id_, first_select)
  823. else:
  824. return '%s_month' % id_
  825. def value_from_datadict(self, data, files, name):
  826. y = data.get(self.year_field % name)
  827. m = data.get(self.month_field % name)
  828. d = data.get(self.day_field % name)
  829. if y == m == d == "0":
  830. return None
  831. if y and m and d:
  832. if settings.USE_L10N:
  833. input_format = get_format('DATE_INPUT_FORMATS')[0]
  834. try:
  835. date_value = datetime.date(int(y), int(m), int(d))
  836. except ValueError:
  837. return '%s-%s-%s' % (y, m, d)
  838. else:
  839. date_value = datetime_safe.new_date(date_value)
  840. return date_value.strftime(input_format)
  841. else:
  842. return '%s-%s-%s' % (y, m, d)
  843. return data.get(name)
  844. def create_select(self, name, field, value, val, choices, none_value):
  845. if 'id' in self.attrs:
  846. id_ = self.attrs['id']
  847. else:
  848. id_ = 'id_%s' % name
  849. if not self.is_required:
  850. choices.insert(0, none_value)
  851. local_attrs = self.build_attrs(id=field % id_)
  852. s = self.select_widget(choices=choices)
  853. select_html = s.render(field % name, val, local_attrs)
  854. return select_html