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.

utils.py 5.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import json
  2. from collections import UserList
  3. from django.conf import settings
  4. from django.core.exceptions import ValidationError # backwards compatibility
  5. from django.utils import timezone
  6. from django.utils.html import escape, format_html, format_html_join, html_safe
  7. from django.utils.translation import gettext_lazy as _
  8. def pretty_name(name):
  9. """Convert 'first_name' to 'First name'."""
  10. if not name:
  11. return ''
  12. return name.replace('_', ' ').capitalize()
  13. def flatatt(attrs):
  14. """
  15. Convert a dictionary of attributes to a single string.
  16. The returned string will contain a leading space followed by key="value",
  17. XML-style pairs. In the case of a boolean value, the key will appear
  18. without a value. It is assumed that the keys do not need to be
  19. XML-escaped. If the passed dictionary is empty, then return an empty
  20. string.
  21. The result is passed through 'mark_safe' (by way of 'format_html_join').
  22. """
  23. key_value_attrs = []
  24. boolean_attrs = []
  25. for attr, value in attrs.items():
  26. if isinstance(value, bool):
  27. if value:
  28. boolean_attrs.append((attr,))
  29. elif value is not None:
  30. key_value_attrs.append((attr, value))
  31. return (
  32. format_html_join('', ' {}="{}"', sorted(key_value_attrs)) +
  33. format_html_join('', ' {}', sorted(boolean_attrs))
  34. )
  35. @html_safe
  36. class ErrorDict(dict):
  37. """
  38. A collection of errors that knows how to display itself in various formats.
  39. The dictionary keys are the field names, and the values are the errors.
  40. """
  41. def as_data(self):
  42. return {f: e.as_data() for f, e in self.items()}
  43. def get_json_data(self, escape_html=False):
  44. return {f: e.get_json_data(escape_html) for f, e in self.items()}
  45. def as_json(self, escape_html=False):
  46. return json.dumps(self.get_json_data(escape_html))
  47. def as_ul(self):
  48. if not self:
  49. return ''
  50. return format_html(
  51. '<ul class="errorlist">{}</ul>',
  52. format_html_join('', '<li>{}{}</li>', self.items())
  53. )
  54. def as_text(self):
  55. output = []
  56. for field, errors in self.items():
  57. output.append('* %s' % field)
  58. output.append('\n'.join(' * %s' % e for e in errors))
  59. return '\n'.join(output)
  60. def __str__(self):
  61. return self.as_ul()
  62. @html_safe
  63. class ErrorList(UserList, list):
  64. """
  65. A collection of errors that knows how to display itself in various formats.
  66. """
  67. def __init__(self, initlist=None, error_class=None):
  68. super().__init__(initlist)
  69. if error_class is None:
  70. self.error_class = 'errorlist'
  71. else:
  72. self.error_class = 'errorlist {}'.format(error_class)
  73. def as_data(self):
  74. return ValidationError(self.data).error_list
  75. def get_json_data(self, escape_html=False):
  76. errors = []
  77. for error in self.as_data():
  78. message = next(iter(error))
  79. errors.append({
  80. 'message': escape(message) if escape_html else message,
  81. 'code': error.code or '',
  82. })
  83. return errors
  84. def as_json(self, escape_html=False):
  85. return json.dumps(self.get_json_data(escape_html))
  86. def as_ul(self):
  87. if not self.data:
  88. return ''
  89. return format_html(
  90. '<ul class="{}">{}</ul>',
  91. self.error_class,
  92. format_html_join('', '<li>{}</li>', ((e,) for e in self))
  93. )
  94. def as_text(self):
  95. return '\n'.join('* %s' % e for e in self)
  96. def __str__(self):
  97. return self.as_ul()
  98. def __repr__(self):
  99. return repr(list(self))
  100. def __contains__(self, item):
  101. return item in list(self)
  102. def __eq__(self, other):
  103. return list(self) == other
  104. def __getitem__(self, i):
  105. error = self.data[i]
  106. if isinstance(error, ValidationError):
  107. return next(iter(error))
  108. return error
  109. def __reduce_ex__(self, *args, **kwargs):
  110. # The `list` reduce function returns an iterator as the fourth element
  111. # that is normally used for repopulating. Since we only inherit from
  112. # `list` for `isinstance` backward compatibility (Refs #17413) we
  113. # nullify this iterator as it would otherwise result in duplicate
  114. # entries. (Refs #23594)
  115. info = super(UserList, self).__reduce_ex__(*args, **kwargs)
  116. return info[:3] + (None, None)
  117. # Utilities for time zone support in DateTimeField et al.
  118. def from_current_timezone(value):
  119. """
  120. When time zone support is enabled, convert naive datetimes
  121. entered in the current time zone to aware datetimes.
  122. """
  123. if settings.USE_TZ and value is not None and timezone.is_naive(value):
  124. current_timezone = timezone.get_current_timezone()
  125. try:
  126. return timezone.make_aware(value, current_timezone)
  127. except Exception as exc:
  128. raise ValidationError(
  129. _('%(datetime)s couldn\'t be interpreted '
  130. 'in time zone %(current_timezone)s; it '
  131. 'may be ambiguous or it may not exist.'),
  132. code='ambiguous_timezone',
  133. params={'datetime': value, 'current_timezone': current_timezone}
  134. ) from exc
  135. return value
  136. def to_current_timezone(value):
  137. """
  138. When time zone support is enabled, convert aware datetimes
  139. to naive datetimes in the current time zone for display.
  140. """
  141. if settings.USE_TZ and value is not None and timezone.is_aware(value):
  142. return timezone.make_naive(value)
  143. return value