widgets.py 36 KB

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