widgets.py 32 KB

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