defaultfilters.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. """Default variable filters."""
  2. import random as random_module
  3. import re
  4. import types
  5. from decimal import ROUND_HALF_UP, Context, Decimal, InvalidOperation
  6. from functools import wraps
  7. from operator import itemgetter
  8. from pprint import pformat
  9. from urllib.parse import quote
  10. from django.utils import formats
  11. from django.utils.dateformat import format, time_format
  12. from django.utils.encoding import iri_to_uri
  13. from django.utils.html import (
  14. avoid_wrapping, conditional_escape, escape, escapejs,
  15. json_script as _json_script, linebreaks, strip_tags, urlize as _urlize,
  16. )
  17. from django.utils.safestring import SafeData, mark_safe
  18. from django.utils.text import (
  19. Truncator, normalize_newlines, phone2numeric, slugify as _slugify, wrap,
  20. )
  21. from django.utils.timesince import timesince, timeuntil
  22. from django.utils.translation import gettext, ngettext
  23. from .base import Variable, VariableDoesNotExist
  24. from .library import Library
  25. register = Library()
  26. #######################
  27. # STRING DECORATOR #
  28. #######################
  29. def stringfilter(func):
  30. """
  31. Decorator for filters which should only receive strings. The object
  32. passed as the first positional argument will be converted to a string.
  33. """
  34. def _dec(*args, **kwargs):
  35. args = list(args)
  36. args[0] = str(args[0])
  37. if (isinstance(args[0], SafeData) and
  38. getattr(_dec._decorated_function, 'is_safe', False)):
  39. return mark_safe(func(*args, **kwargs))
  40. return func(*args, **kwargs)
  41. # Include a reference to the real function (used to check original
  42. # arguments by the template parser, and to bear the 'is_safe' attribute
  43. # when multiple decorators are applied).
  44. _dec._decorated_function = getattr(func, '_decorated_function', func)
  45. return wraps(func)(_dec)
  46. ###################
  47. # STRINGS #
  48. ###################
  49. @register.filter(is_safe=True)
  50. @stringfilter
  51. def addslashes(value):
  52. """
  53. Add slashes before quotes. Useful for escaping strings in CSV, for
  54. example. Less useful for escaping JavaScript; use the ``escapejs``
  55. filter instead.
  56. """
  57. return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
  58. @register.filter(is_safe=True)
  59. @stringfilter
  60. def capfirst(value):
  61. """Capitalize the first character of the value."""
  62. return value and value[0].upper() + value[1:]
  63. @register.filter("escapejs")
  64. @stringfilter
  65. def escapejs_filter(value):
  66. """Hex encode characters for use in JavaScript strings."""
  67. return escapejs(value)
  68. @register.filter(is_safe=True)
  69. def json_script(value, element_id):
  70. """
  71. Output value JSON-encoded, wrapped in a <script type="application/json">
  72. tag.
  73. """
  74. return _json_script(value, element_id)
  75. @register.filter(is_safe=True)
  76. def floatformat(text, arg=-1):
  77. """
  78. Display a float to a specified number of decimal places.
  79. If called without an argument, display the floating point number with one
  80. decimal place -- but only if there's a decimal place to be displayed:
  81. * num1 = 34.23234
  82. * num2 = 34.00000
  83. * num3 = 34.26000
  84. * {{ num1|floatformat }} displays "34.2"
  85. * {{ num2|floatformat }} displays "34"
  86. * {{ num3|floatformat }} displays "34.3"
  87. If arg is positive, always display exactly arg number of decimal places:
  88. * {{ num1|floatformat:3 }} displays "34.232"
  89. * {{ num2|floatformat:3 }} displays "34.000"
  90. * {{ num3|floatformat:3 }} displays "34.260"
  91. If arg is negative, display arg number of decimal places -- but only if
  92. there are places to be displayed:
  93. * {{ num1|floatformat:"-3" }} displays "34.232"
  94. * {{ num2|floatformat:"-3" }} displays "34"
  95. * {{ num3|floatformat:"-3" }} displays "34.260"
  96. If arg has the 'g' suffix, force the result to be grouped by the
  97. THOUSAND_SEPARATOR for the active locale. When the active locale is
  98. en (English):
  99. * {{ 6666.6666|floatformat:"2g" }} displays "6,666.67"
  100. * {{ 10000|floatformat:"g" }} displays "10,000"
  101. If arg has the 'u' suffix, force the result to be unlocalized. When the
  102. active locale is pl (Polish):
  103. * {{ 66666.6666|floatformat:"2" }} displays "66666,67"
  104. * {{ 66666.6666|floatformat:"2u" }} displays "66666.67"
  105. If the input float is infinity or NaN, display the string representation
  106. of that value.
  107. """
  108. force_grouping = False
  109. use_l10n = True
  110. if isinstance(arg, str):
  111. last_char = arg[-1]
  112. if arg[-2:] in {'gu', 'ug'}:
  113. force_grouping = True
  114. use_l10n = False
  115. arg = arg[:-2] or -1
  116. elif last_char == 'g':
  117. force_grouping = True
  118. arg = arg[:-1] or -1
  119. elif last_char == 'u':
  120. use_l10n = False
  121. arg = arg[:-1] or -1
  122. try:
  123. input_val = repr(text)
  124. d = Decimal(input_val)
  125. except InvalidOperation:
  126. try:
  127. d = Decimal(str(float(text)))
  128. except (ValueError, InvalidOperation, TypeError):
  129. return ''
  130. try:
  131. p = int(arg)
  132. except ValueError:
  133. return input_val
  134. try:
  135. m = int(d) - d
  136. except (ValueError, OverflowError, InvalidOperation):
  137. return input_val
  138. if not m and p < 0:
  139. return mark_safe(formats.number_format(
  140. '%d' % (int(d)),
  141. 0,
  142. use_l10n=use_l10n,
  143. force_grouping=force_grouping,
  144. ))
  145. exp = Decimal(1).scaleb(-abs(p))
  146. # Set the precision high enough to avoid an exception (#15789).
  147. tupl = d.as_tuple()
  148. units = len(tupl[1])
  149. units += -tupl[2] if m else tupl[2]
  150. prec = abs(p) + units + 1
  151. # Avoid conversion to scientific notation by accessing `sign`, `digits`,
  152. # and `exponent` from Decimal.as_tuple() directly.
  153. rounded_d = d.quantize(exp, ROUND_HALF_UP, Context(prec=prec))
  154. sign, digits, exponent = rounded_d.as_tuple()
  155. digits = [str(digit) for digit in reversed(digits)]
  156. while len(digits) <= abs(exponent):
  157. digits.append('0')
  158. digits.insert(-exponent, '.')
  159. if sign and rounded_d:
  160. digits.append('-')
  161. number = ''.join(reversed(digits))
  162. return mark_safe(formats.number_format(
  163. number,
  164. abs(p),
  165. use_l10n=use_l10n,
  166. force_grouping=force_grouping,
  167. ))
  168. @register.filter(is_safe=True)
  169. @stringfilter
  170. def iriencode(value):
  171. """Escape an IRI value for use in a URL."""
  172. return iri_to_uri(value)
  173. @register.filter(is_safe=True, needs_autoescape=True)
  174. @stringfilter
  175. def linenumbers(value, autoescape=True):
  176. """Display text with line numbers."""
  177. lines = value.split('\n')
  178. # Find the maximum width of the line count, for use with zero padding
  179. # string format command
  180. width = str(len(str(len(lines))))
  181. if not autoescape or isinstance(value, SafeData):
  182. for i, line in enumerate(lines):
  183. lines[i] = ("%0" + width + "d. %s") % (i + 1, line)
  184. else:
  185. for i, line in enumerate(lines):
  186. lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line))
  187. return mark_safe('\n'.join(lines))
  188. @register.filter(is_safe=True)
  189. @stringfilter
  190. def lower(value):
  191. """Convert a string into all lowercase."""
  192. return value.lower()
  193. @register.filter(is_safe=False)
  194. @stringfilter
  195. def make_list(value):
  196. """
  197. Return the value turned into a list.
  198. For an integer, it's a list of digits.
  199. For a string, it's a list of characters.
  200. """
  201. return list(value)
  202. @register.filter(is_safe=True)
  203. @stringfilter
  204. def slugify(value):
  205. """
  206. Convert to ASCII. Convert spaces to hyphens. Remove characters that aren't
  207. alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip
  208. leading and trailing whitespace.
  209. """
  210. return _slugify(value)
  211. @register.filter(is_safe=True)
  212. def stringformat(value, arg):
  213. """
  214. Format the variable according to the arg, a string formatting specifier.
  215. This specifier uses Python string formatting syntax, with the exception
  216. that the leading "%" is dropped.
  217. See https://docs.python.org/library/stdtypes.html#printf-style-string-formatting
  218. for documentation of Python string formatting.
  219. """
  220. if isinstance(value, tuple):
  221. value = str(value)
  222. try:
  223. return ("%" + str(arg)) % value
  224. except (ValueError, TypeError):
  225. return ""
  226. @register.filter(is_safe=True)
  227. @stringfilter
  228. def title(value):
  229. """Convert a string into titlecase."""
  230. t = re.sub("([a-z])'([A-Z])", lambda m: m[0].lower(), value.title())
  231. return re.sub(r'\d([A-Z])', lambda m: m[0].lower(), t)
  232. @register.filter(is_safe=True)
  233. @stringfilter
  234. def truncatechars(value, arg):
  235. """Truncate a string after `arg` number of characters."""
  236. try:
  237. length = int(arg)
  238. except ValueError: # Invalid literal for int().
  239. return value # Fail silently.
  240. return Truncator(value).chars(length)
  241. @register.filter(is_safe=True)
  242. @stringfilter
  243. def truncatechars_html(value, arg):
  244. """
  245. Truncate HTML after `arg` number of chars.
  246. Preserve newlines in the HTML.
  247. """
  248. try:
  249. length = int(arg)
  250. except ValueError: # invalid literal for int()
  251. return value # Fail silently.
  252. return Truncator(value).chars(length, html=True)
  253. @register.filter(is_safe=True)
  254. @stringfilter
  255. def truncatewords(value, arg):
  256. """
  257. Truncate a string after `arg` number of words.
  258. Remove newlines within the string.
  259. """
  260. try:
  261. length = int(arg)
  262. except ValueError: # Invalid literal for int().
  263. return value # Fail silently.
  264. return Truncator(value).words(length, truncate=' …')
  265. @register.filter(is_safe=True)
  266. @stringfilter
  267. def truncatewords_html(value, arg):
  268. """
  269. Truncate HTML after `arg` number of words.
  270. Preserve newlines in the HTML.
  271. """
  272. try:
  273. length = int(arg)
  274. except ValueError: # invalid literal for int()
  275. return value # Fail silently.
  276. return Truncator(value).words(length, html=True, truncate=' …')
  277. @register.filter(is_safe=False)
  278. @stringfilter
  279. def upper(value):
  280. """Convert a string into all uppercase."""
  281. return value.upper()
  282. @register.filter(is_safe=False)
  283. @stringfilter
  284. def urlencode(value, safe=None):
  285. """
  286. Escape a value for use in a URL.
  287. The ``safe`` parameter determines the characters which should not be
  288. escaped by Python's quote() function. If not provided, use the default safe
  289. characters (but an empty string can be provided when *all* characters
  290. should be escaped).
  291. """
  292. kwargs = {}
  293. if safe is not None:
  294. kwargs['safe'] = safe
  295. return quote(value, **kwargs)
  296. @register.filter(is_safe=True, needs_autoescape=True)
  297. @stringfilter
  298. def urlize(value, autoescape=True):
  299. """Convert URLs in plain text into clickable links."""
  300. return mark_safe(_urlize(value, nofollow=True, autoescape=autoescape))
  301. @register.filter(is_safe=True, needs_autoescape=True)
  302. @stringfilter
  303. def urlizetrunc(value, limit, autoescape=True):
  304. """
  305. Convert URLs into clickable links, truncating URLs to the given character
  306. limit, and adding 'rel=nofollow' attribute to discourage spamming.
  307. Argument: Length to truncate URLs to.
  308. """
  309. return mark_safe(_urlize(value, trim_url_limit=int(limit), nofollow=True, autoescape=autoescape))
  310. @register.filter(is_safe=False)
  311. @stringfilter
  312. def wordcount(value):
  313. """Return the number of words."""
  314. return len(value.split())
  315. @register.filter(is_safe=True)
  316. @stringfilter
  317. def wordwrap(value, arg):
  318. """Wrap words at `arg` line length."""
  319. return wrap(value, int(arg))
  320. @register.filter(is_safe=True)
  321. @stringfilter
  322. def ljust(value, arg):
  323. """Left-align the value in a field of a given width."""
  324. return value.ljust(int(arg))
  325. @register.filter(is_safe=True)
  326. @stringfilter
  327. def rjust(value, arg):
  328. """Right-align the value in a field of a given width."""
  329. return value.rjust(int(arg))
  330. @register.filter(is_safe=True)
  331. @stringfilter
  332. def center(value, arg):
  333. """Center the value in a field of a given width."""
  334. return value.center(int(arg))
  335. @register.filter
  336. @stringfilter
  337. def cut(value, arg):
  338. """Remove all values of arg from the given string."""
  339. safe = isinstance(value, SafeData)
  340. value = value.replace(arg, '')
  341. if safe and arg != ';':
  342. return mark_safe(value)
  343. return value
  344. ###################
  345. # HTML STRINGS #
  346. ###################
  347. @register.filter("escape", is_safe=True)
  348. @stringfilter
  349. def escape_filter(value):
  350. """Mark the value as a string that should be auto-escaped."""
  351. return conditional_escape(value)
  352. @register.filter(is_safe=True)
  353. @stringfilter
  354. def force_escape(value):
  355. """
  356. Escape a string's HTML. Return a new string containing the escaped
  357. characters (as opposed to "escape", which marks the content for later
  358. possible escaping).
  359. """
  360. return escape(value)
  361. @register.filter("linebreaks", is_safe=True, needs_autoescape=True)
  362. @stringfilter
  363. def linebreaks_filter(value, autoescape=True):
  364. """
  365. Replace line breaks in plain text with appropriate HTML; a single
  366. newline becomes an HTML line break (``<br>``) and a new line
  367. followed by a blank line becomes a paragraph break (``</p>``).
  368. """
  369. autoescape = autoescape and not isinstance(value, SafeData)
  370. return mark_safe(linebreaks(value, autoescape))
  371. @register.filter(is_safe=True, needs_autoescape=True)
  372. @stringfilter
  373. def linebreaksbr(value, autoescape=True):
  374. """
  375. Convert all newlines in a piece of plain text to HTML line breaks
  376. (``<br>``).
  377. """
  378. autoescape = autoescape and not isinstance(value, SafeData)
  379. value = normalize_newlines(value)
  380. if autoescape:
  381. value = escape(value)
  382. return mark_safe(value.replace('\n', '<br>'))
  383. @register.filter(is_safe=True)
  384. @stringfilter
  385. def safe(value):
  386. """Mark the value as a string that should not be auto-escaped."""
  387. return mark_safe(value)
  388. @register.filter(is_safe=True)
  389. def safeseq(value):
  390. """
  391. A "safe" filter for sequences. Mark each element in the sequence,
  392. individually, as safe, after converting them to strings. Return a list
  393. with the results.
  394. """
  395. return [mark_safe(obj) for obj in value]
  396. @register.filter(is_safe=True)
  397. @stringfilter
  398. def striptags(value):
  399. """Strip all [X]HTML tags."""
  400. return strip_tags(value)
  401. ###################
  402. # LISTS #
  403. ###################
  404. def _property_resolver(arg):
  405. """
  406. When arg is convertible to float, behave like operator.itemgetter(arg)
  407. Otherwise, behave like Variable(arg).resolve
  408. >>> _property_resolver(1)('abc')
  409. 'b'
  410. >>> _property_resolver('1')('abc')
  411. Traceback (most recent call last):
  412. ...
  413. TypeError: string indices must be integers
  414. >>> class Foo:
  415. ... a = 42
  416. ... b = 3.14
  417. ... c = 'Hey!'
  418. >>> _property_resolver('b')(Foo())
  419. 3.14
  420. """
  421. try:
  422. float(arg)
  423. except ValueError:
  424. return Variable(arg).resolve
  425. else:
  426. return itemgetter(arg)
  427. @register.filter(is_safe=False)
  428. def dictsort(value, arg):
  429. """
  430. Given a list of dicts, return that list sorted by the property given in
  431. the argument.
  432. """
  433. try:
  434. return sorted(value, key=_property_resolver(arg))
  435. except (TypeError, VariableDoesNotExist):
  436. return ''
  437. @register.filter(is_safe=False)
  438. def dictsortreversed(value, arg):
  439. """
  440. Given a list of dicts, return that list sorted in reverse order by the
  441. property given in the argument.
  442. """
  443. try:
  444. return sorted(value, key=_property_resolver(arg), reverse=True)
  445. except (TypeError, VariableDoesNotExist):
  446. return ''
  447. @register.filter(is_safe=False)
  448. def first(value):
  449. """Return the first item in a list."""
  450. try:
  451. return value[0]
  452. except IndexError:
  453. return ''
  454. @register.filter(is_safe=True, needs_autoescape=True)
  455. def join(value, arg, autoescape=True):
  456. """Join a list with a string, like Python's ``str.join(list)``."""
  457. try:
  458. if autoescape:
  459. value = [conditional_escape(v) for v in value]
  460. data = conditional_escape(arg).join(value)
  461. except TypeError: # Fail silently if arg isn't iterable.
  462. return value
  463. return mark_safe(data)
  464. @register.filter(is_safe=True)
  465. def last(value):
  466. """Return the last item in a list."""
  467. try:
  468. return value[-1]
  469. except IndexError:
  470. return ''
  471. @register.filter(is_safe=False)
  472. def length(value):
  473. """Return the length of the value - useful for lists."""
  474. try:
  475. return len(value)
  476. except (ValueError, TypeError):
  477. return 0
  478. @register.filter(is_safe=False)
  479. def length_is(value, arg):
  480. """Return a boolean of whether the value's length is the argument."""
  481. try:
  482. return len(value) == int(arg)
  483. except (ValueError, TypeError):
  484. return ''
  485. @register.filter(is_safe=True)
  486. def random(value):
  487. """Return a random item from the list."""
  488. return random_module.choice(value)
  489. @register.filter("slice", is_safe=True)
  490. def slice_filter(value, arg):
  491. """
  492. Return a slice of the list using the same syntax as Python's list slicing.
  493. """
  494. try:
  495. bits = []
  496. for x in str(arg).split(':'):
  497. if not x:
  498. bits.append(None)
  499. else:
  500. bits.append(int(x))
  501. return value[slice(*bits)]
  502. except (ValueError, TypeError):
  503. return value # Fail silently.
  504. @register.filter(is_safe=True, needs_autoescape=True)
  505. def unordered_list(value, autoescape=True):
  506. """
  507. Recursively take a self-nested list and return an HTML unordered list --
  508. WITHOUT opening and closing <ul> tags.
  509. Assume the list is in the proper format. For example, if ``var`` contains:
  510. ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
  511. ``{{ var|unordered_list }}`` returns::
  512. <li>States
  513. <ul>
  514. <li>Kansas
  515. <ul>
  516. <li>Lawrence</li>
  517. <li>Topeka</li>
  518. </ul>
  519. </li>
  520. <li>Illinois</li>
  521. </ul>
  522. </li>
  523. """
  524. if autoescape:
  525. escaper = conditional_escape
  526. else:
  527. def escaper(x):
  528. return x
  529. def walk_items(item_list):
  530. item_iterator = iter(item_list)
  531. try:
  532. item = next(item_iterator)
  533. while True:
  534. try:
  535. next_item = next(item_iterator)
  536. except StopIteration:
  537. yield item, None
  538. break
  539. if isinstance(next_item, (list, tuple, types.GeneratorType)):
  540. try:
  541. iter(next_item)
  542. except TypeError:
  543. pass
  544. else:
  545. yield item, next_item
  546. item = next(item_iterator)
  547. continue
  548. yield item, None
  549. item = next_item
  550. except StopIteration:
  551. pass
  552. def list_formatter(item_list, tabs=1):
  553. indent = '\t' * tabs
  554. output = []
  555. for item, children in walk_items(item_list):
  556. sublist = ''
  557. if children:
  558. sublist = '\n%s<ul>\n%s\n%s</ul>\n%s' % (
  559. indent, list_formatter(children, tabs + 1), indent, indent)
  560. output.append('%s<li>%s%s</li>' % (
  561. indent, escaper(item), sublist))
  562. return '\n'.join(output)
  563. return mark_safe(list_formatter(value))
  564. ###################
  565. # INTEGERS #
  566. ###################
  567. @register.filter(is_safe=False)
  568. def add(value, arg):
  569. """Add the arg to the value."""
  570. try:
  571. return int(value) + int(arg)
  572. except (ValueError, TypeError):
  573. try:
  574. return value + arg
  575. except Exception:
  576. return ''
  577. @register.filter(is_safe=False)
  578. def get_digit(value, arg):
  579. """
  580. Given a whole number, return the requested digit of it, where 1 is the
  581. right-most digit, 2 is the second-right-most digit, etc. Return the
  582. original value for invalid input (if input or argument is not an integer,
  583. or if argument is less than 1). Otherwise, output is always an integer.
  584. """
  585. try:
  586. arg = int(arg)
  587. value = int(value)
  588. except ValueError:
  589. return value # Fail silently for an invalid argument
  590. if arg < 1:
  591. return value
  592. try:
  593. return int(str(value)[-arg])
  594. except IndexError:
  595. return 0
  596. ###################
  597. # DATES #
  598. ###################
  599. @register.filter(expects_localtime=True, is_safe=False)
  600. def date(value, arg=None):
  601. """Format a date according to the given format."""
  602. if value in (None, ''):
  603. return ''
  604. try:
  605. return formats.date_format(value, arg)
  606. except AttributeError:
  607. try:
  608. return format(value, arg)
  609. except AttributeError:
  610. return ''
  611. @register.filter(expects_localtime=True, is_safe=False)
  612. def time(value, arg=None):
  613. """Format a time according to the given format."""
  614. if value in (None, ''):
  615. return ''
  616. try:
  617. return formats.time_format(value, arg)
  618. except (AttributeError, TypeError):
  619. try:
  620. return time_format(value, arg)
  621. except (AttributeError, TypeError):
  622. return ''
  623. @register.filter("timesince", is_safe=False)
  624. def timesince_filter(value, arg=None):
  625. """Format a date as the time since that date (i.e. "4 days, 6 hours")."""
  626. if not value:
  627. return ''
  628. try:
  629. if arg:
  630. return timesince(value, arg)
  631. return timesince(value)
  632. except (ValueError, TypeError):
  633. return ''
  634. @register.filter("timeuntil", is_safe=False)
  635. def timeuntil_filter(value, arg=None):
  636. """Format a date as the time until that date (i.e. "4 days, 6 hours")."""
  637. if not value:
  638. return ''
  639. try:
  640. return timeuntil(value, arg)
  641. except (ValueError, TypeError):
  642. return ''
  643. ###################
  644. # LOGIC #
  645. ###################
  646. @register.filter(is_safe=False)
  647. def default(value, arg):
  648. """If value is unavailable, use given default."""
  649. return value or arg
  650. @register.filter(is_safe=False)
  651. def default_if_none(value, arg):
  652. """If value is None, use given default."""
  653. if value is None:
  654. return arg
  655. return value
  656. @register.filter(is_safe=False)
  657. def divisibleby(value, arg):
  658. """Return True if the value is divisible by the argument."""
  659. return int(value) % int(arg) == 0
  660. @register.filter(is_safe=False)
  661. def yesno(value, arg=None):
  662. """
  663. Given a string mapping values for true, false, and (optionally) None,
  664. return one of those strings according to the value:
  665. ========== ====================== ==================================
  666. Value Argument Outputs
  667. ========== ====================== ==================================
  668. ``True`` ``"yeah,no,maybe"`` ``yeah``
  669. ``False`` ``"yeah,no,maybe"`` ``no``
  670. ``None`` ``"yeah,no,maybe"`` ``maybe``
  671. ``None`` ``"yeah,no"`` ``"no"`` (converts None to False
  672. if no mapping for None is given.
  673. ========== ====================== ==================================
  674. """
  675. if arg is None:
  676. # Translators: Please do not add spaces around commas.
  677. arg = gettext('yes,no,maybe')
  678. bits = arg.split(',')
  679. if len(bits) < 2:
  680. return value # Invalid arg.
  681. try:
  682. yes, no, maybe = bits
  683. except ValueError:
  684. # Unpack list of wrong size (no "maybe" value provided).
  685. yes, no, maybe = bits[0], bits[1], bits[1]
  686. if value is None:
  687. return maybe
  688. if value:
  689. return yes
  690. return no
  691. ###################
  692. # MISC #
  693. ###################
  694. @register.filter(is_safe=True)
  695. def filesizeformat(bytes_):
  696. """
  697. Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
  698. 102 bytes, etc.).
  699. """
  700. try:
  701. bytes_ = int(bytes_)
  702. except (TypeError, ValueError, UnicodeDecodeError):
  703. value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}
  704. return avoid_wrapping(value)
  705. def filesize_number_format(value):
  706. return formats.number_format(round(value, 1), 1)
  707. KB = 1 << 10
  708. MB = 1 << 20
  709. GB = 1 << 30
  710. TB = 1 << 40
  711. PB = 1 << 50
  712. negative = bytes_ < 0
  713. if negative:
  714. bytes_ = -bytes_ # Allow formatting of negative numbers.
  715. if bytes_ < KB:
  716. value = ngettext("%(size)d byte", "%(size)d bytes", bytes_) % {'size': bytes_}
  717. elif bytes_ < MB:
  718. value = gettext("%s KB") % filesize_number_format(bytes_ / KB)
  719. elif bytes_ < GB:
  720. value = gettext("%s MB") % filesize_number_format(bytes_ / MB)
  721. elif bytes_ < TB:
  722. value = gettext("%s GB") % filesize_number_format(bytes_ / GB)
  723. elif bytes_ < PB:
  724. value = gettext("%s TB") % filesize_number_format(bytes_ / TB)
  725. else:
  726. value = gettext("%s PB") % filesize_number_format(bytes_ / PB)
  727. if negative:
  728. value = "-%s" % value
  729. return avoid_wrapping(value)
  730. @register.filter(is_safe=False)
  731. def pluralize(value, arg='s'):
  732. """
  733. Return a plural suffix if the value is not 1, '1', or an object of
  734. length 1. By default, use 's' as the suffix:
  735. * If value is 0, vote{{ value|pluralize }} display "votes".
  736. * If value is 1, vote{{ value|pluralize }} display "vote".
  737. * If value is 2, vote{{ value|pluralize }} display "votes".
  738. If an argument is provided, use that string instead:
  739. * If value is 0, class{{ value|pluralize:"es" }} display "classes".
  740. * If value is 1, class{{ value|pluralize:"es" }} display "class".
  741. * If value is 2, class{{ value|pluralize:"es" }} display "classes".
  742. If the provided argument contains a comma, use the text before the comma
  743. for the singular case and the text after the comma for the plural case:
  744. * If value is 0, cand{{ value|pluralize:"y,ies" }} display "candies".
  745. * If value is 1, cand{{ value|pluralize:"y,ies" }} display "candy".
  746. * If value is 2, cand{{ value|pluralize:"y,ies" }} display "candies".
  747. """
  748. if ',' not in arg:
  749. arg = ',' + arg
  750. bits = arg.split(',')
  751. if len(bits) > 2:
  752. return ''
  753. singular_suffix, plural_suffix = bits[:2]
  754. try:
  755. return singular_suffix if float(value) == 1 else plural_suffix
  756. except ValueError: # Invalid string that's not a number.
  757. pass
  758. except TypeError: # Value isn't a string or a number; maybe it's a list?
  759. try:
  760. return singular_suffix if len(value) == 1 else plural_suffix
  761. except TypeError: # len() of unsized object.
  762. pass
  763. return ''
  764. @register.filter("phone2numeric", is_safe=True)
  765. def phone2numeric_filter(value):
  766. """Take a phone number and converts it in to its numerical equivalent."""
  767. return phone2numeric(value)
  768. @register.filter(is_safe=True)
  769. def pprint(value):
  770. """A wrapper around pprint.pprint -- for debugging, really."""
  771. try:
  772. return pformat(value)
  773. except Exception as e:
  774. return "Error in formatting: %s: %s" % (e.__class__.__name__, e)