widgets.py 31 KB

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