Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

widgets.py 36KB

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