widgets.py 36 KB

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